{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#@title Copyright 2022 Google LLC, licensed under the Apache License, Version 2.0 (the \"License\")\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import glob \n",
    "import math\n",
    "import sys\n",
    "import os\n",
    "import cv2\n",
    "import glob\n",
    "import numpy as np\n",
    "import pickle\n",
    "import matplotlib.pylab as plt\n",
    "import time\n",
    "import random\n",
    "import math\n",
    "import collections\n",
    "import queue\n",
    "import collections\n",
    "import threading\n",
    "import functools\n",
    "from tqdm.notebook import tqdm\n",
    "from typing import Dict, Type, Any, Callable, Union, List, Optional\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "import torch\n",
    "from torch import nn\n",
    "import torch.optim as optim\n",
    "from torch.nn import functional as F\n",
    "from torch.autograd import Variable\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "import torch.backends.cudnn as cudnn\n",
    "from torchinfo import summary\n",
    "import torch.utils.model_zoo as model_zoo\n",
    "from torch.nn.parallel.data_parallel import DataParallel\n",
    "from torch.nn.modules.batchnorm import _BatchNorm\n",
    "from torch.nn.parallel._functions import ReduceAddCoalesced, Broadcast"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Synchorised Batch Norm**\n",
    "Citation : https://github.com/vacancy/Synchronized-BatchNorm-PyTorch\n",
    "Implements a Synchronised Batch Norm for distributed learning (using DataParallel here)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class FutureResult(object):\n",
    "    \"\"\"A thread-safe future implementation. Used only as one-to-one pipe.\"\"\"\n",
    "\n",
    "    def __init__(self):\n",
    "        self._result = None\n",
    "        self._lock = threading.Lock()\n",
    "        self._cond = threading.Condition(self._lock)\n",
    "\n",
    "    def put(self, result):\n",
    "        with self._lock:\n",
    "            assert self._result is None, 'Previous result has\\'t been fetched.'\n",
    "            self._result = result\n",
    "            self._cond.notify()\n",
    "\n",
    "    def get(self):\n",
    "        with self._lock:\n",
    "            if self._result is None:\n",
    "                self._cond.wait()\n",
    "\n",
    "            res = self._result\n",
    "            self._result = None\n",
    "            return res\n",
    "\n",
    "\n",
    "_MasterRegistry = collections.namedtuple('MasterRegistry', ['result'])\n",
    "_SlavePipeBase = collections.namedtuple('_SlavePipeBase', ['identifier', 'queue', 'result'])\n",
    "\n",
    "\n",
    "class SlavePipe(_SlavePipeBase):\n",
    "    \"\"\"Pipe for master-slave communication.\"\"\"\n",
    "\n",
    "    def run_slave(self, msg):\n",
    "        self.queue.put((self.identifier, msg))\n",
    "        ret = self.result.get()\n",
    "        self.queue.put(True)\n",
    "        return ret\n",
    "\n",
    "\n",
    "class SyncMaster(object):\n",
    "    \"\"\"An abstract `SyncMaster` object.\n",
    "    - During the replication, as the data parallel will trigger an callback of each module, all slave devices should\n",
    "    call `register(id)` and obtain an `SlavePipe` to communicate with the master.\n",
    "    - During the forward pass, master device invokes `run_master`, all messages from slave devices will be collected,\n",
    "    and passed to a registered callback.\n",
    "    - After receiving the messages, the master device should gather the information and determine to message passed\n",
    "    back to each slave devices.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, master_callback):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            master_callback: a callback to be invoked after having collected messages from slave devices.\n",
    "        \"\"\"\n",
    "        self._master_callback = master_callback\n",
    "        self._queue = queue.Queue()\n",
    "        self._registry = collections.OrderedDict()\n",
    "        self._activated = False\n",
    "\n",
    "    def __getstate__(self):\n",
    "        return {'master_callback': self._master_callback}\n",
    "\n",
    "    def __setstate__(self, state):\n",
    "        self.__init__(state['master_callback'])\n",
    "\n",
    "    def register_slave(self, identifier):\n",
    "        \"\"\"\n",
    "        Register an slave device.\n",
    "        Args:\n",
    "            identifier: an identifier, usually is the device id.\n",
    "        Returns: a `SlavePipe` object which can be used to communicate with the master device.\n",
    "        \"\"\"\n",
    "        if self._activated:\n",
    "            assert self._queue.empty(), 'Queue is not clean before next initialization.'\n",
    "            self._activated = False\n",
    "            self._registry.clear()\n",
    "        future = FutureResult()\n",
    "        self._registry[identifier] = _MasterRegistry(future)\n",
    "        return SlavePipe(identifier, self._queue, future)\n",
    "\n",
    "    def run_master(self, master_msg):\n",
    "        \"\"\"\n",
    "        Main entry for the master device in each forward pass.\n",
    "        The messages were first collected from each devices (including the master device), and then\n",
    "        an callback will be invoked to compute the message to be sent back to each devices\n",
    "        (including the master device).\n",
    "        Args:\n",
    "            master_msg: the message that the master want to send to itself. This will be placed as the first\n",
    "            message when calling `master_callback`. For detailed usage, see `_SynchronizedBatchNorm` for an example.\n",
    "        Returns: the message to be sent back to the master device.\n",
    "        \"\"\"\n",
    "        self._activated = True\n",
    "\n",
    "        intermediates = [(0, master_msg)]\n",
    "        for i in range(self.nr_slaves):\n",
    "            intermediates.append(self._queue.get())\n",
    "\n",
    "        results = self._master_callback(intermediates)\n",
    "        assert results[0][0] == 0, 'The first result should belongs to the master.'\n",
    "\n",
    "        for i, res in results:\n",
    "            if i == 0:\n",
    "                continue\n",
    "            self._registry[i].result.put(res)\n",
    "\n",
    "        for i in range(self.nr_slaves):\n",
    "            assert self._queue.get() is True\n",
    "\n",
    "        return results[0][1]\n",
    "\n",
    "    @property\n",
    "    def nr_slaves(self):\n",
    "        return len(self._registry)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def _sum_ft(tensor):\n",
    "    \"\"\"sum over the first and last dimention\"\"\"\n",
    "    return tensor.sum(dim=0).sum(dim=-1)\n",
    "\n",
    "\n",
    "def _unsqueeze_ft(tensor):\n",
    "    \"\"\"add new dementions at the front and the tail\"\"\"\n",
    "    return tensor.unsqueeze(0).unsqueeze(-1)\n",
    "\n",
    "\n",
    "_ChildMessage = collections.namedtuple('_ChildMessage', ['sum', 'ssum', 'sum_size'])\n",
    "_MasterMessage = collections.namedtuple('_MasterMessage', ['sum', 'inv_std'])\n",
    "\n",
    "\n",
    "class _SynchronizedBatchNorm(_BatchNorm):\n",
    "    def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True):\n",
    "        super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine)\n",
    "\n",
    "        self._sync_master = SyncMaster(self._data_parallel_master)\n",
    "\n",
    "        self._is_parallel = False\n",
    "        self._parallel_id = None\n",
    "        self._slave_pipe = None\n",
    "\n",
    "    def forward(self, input):\n",
    "        # If it is not parallel computation or is in evaluation mode, use PyTorch's implementation.\n",
    "        if not (self._is_parallel and self.training):\n",
    "            return F.batch_norm(\n",
    "                input, self.running_mean, self.running_var, self.weight, self.bias,\n",
    "                self.training, self.momentum, self.eps)\n",
    "\n",
    "        # Resize the input to (B, C, -1).\n",
    "        input_shape = input.size()\n",
    "        input = input.view(input.size(0), self.num_features, -1)\n",
    "\n",
    "        # Compute the sum and square-sum.\n",
    "        sum_size = input.size(0) * input.size(2)\n",
    "        input_sum = _sum_ft(input)\n",
    "        input_ssum = _sum_ft(input ** 2)\n",
    "\n",
    "        # Reduce-and-broadcast the statistics.\n",
    "        if self._parallel_id == 0:\n",
    "            mean, inv_std = self._sync_master.run_master(_ChildMessage(input_sum, input_ssum, sum_size))\n",
    "        else:\n",
    "            mean, inv_std = self._slave_pipe.run_slave(_ChildMessage(input_sum, input_ssum, sum_size))\n",
    "\n",
    "        # Compute the output.\n",
    "        if self.affine:\n",
    "            # MJY:: Fuse the multiplication for speed.\n",
    "            output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std * self.weight) + _unsqueeze_ft(self.bias)\n",
    "        else:\n",
    "            output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std)\n",
    "\n",
    "        # Reshape it.\n",
    "        return output.view(input_shape)\n",
    "\n",
    "    def __data_parallel_replicate__(self, ctx, copy_id):\n",
    "        self._is_parallel = True\n",
    "        self._parallel_id = copy_id\n",
    "\n",
    "        # parallel_id == 0 means master device.\n",
    "        if self._parallel_id == 0:\n",
    "            ctx.sync_master = self._sync_master\n",
    "        else:\n",
    "            self._slave_pipe = ctx.sync_master.register_slave(copy_id)\n",
    "\n",
    "    def _data_parallel_master(self, intermediates):\n",
    "        \"\"\"Reduce the sum and square-sum, compute the statistics, and broadcast it.\"\"\"\n",
    "\n",
    "        # Always using same \"device order\" makes the ReduceAdd operation faster.\n",
    "        # Thanks to:: Tete Xiao (http://tetexiao.com/)\n",
    "        intermediates = sorted(intermediates, key=lambda i: i[1].sum.get_device())\n",
    "\n",
    "        to_reduce = [i[1][:2] for i in intermediates]\n",
    "        to_reduce = [j for i in to_reduce for j in i]  # flatten\n",
    "        target_gpus = [i[1].sum.get_device() for i in intermediates]\n",
    "\n",
    "        sum_size = sum([i[1].sum_size for i in intermediates])\n",
    "        sum_, ssum = ReduceAddCoalesced.apply(target_gpus[0], 2, *to_reduce)\n",
    "        mean, inv_std = self._compute_mean_std(sum_, ssum, sum_size)\n",
    "\n",
    "        broadcasted = Broadcast.apply(target_gpus, mean, inv_std)\n",
    "\n",
    "        outputs = []\n",
    "        for i, rec in enumerate(intermediates):\n",
    "            outputs.append((rec[0], _MasterMessage(*broadcasted[i * 2:i * 2 + 2])))\n",
    "\n",
    "        return outputs\n",
    "\n",
    "    def _compute_mean_std(self, sum_, ssum, size):\n",
    "        \"\"\"Compute the mean and standard-deviation with sum and square-sum. This method\n",
    "        also maintains the moving average on the master device.\"\"\"\n",
    "        assert size > 1, 'BatchNorm computes unbiased standard-deviation, which requires size > 1.'\n",
    "        mean = sum_ / size\n",
    "        sumvar = ssum - sum_ * mean\n",
    "        unbias_var = sumvar / (size - 1)\n",
    "        bias_var = sumvar / size\n",
    "\n",
    "        self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean.data\n",
    "        self.running_var = (1 - self.momentum) * self.running_var + self.momentum * unbias_var.data\n",
    "\n",
    "        return mean, bias_var.clamp(self.eps) ** -0.5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SynchronizedBatchNorm2d(_SynchronizedBatchNorm):\n",
    "    r\"\"\"Applies Batch Normalization over a 4d input that is seen as a mini-batch\n",
    "    of 3d inputs\n",
    "    .. math::\n",
    "        y = \\frac{x - mean[x]}{ \\sqrt{Var[x] + \\epsilon}} * gamma + beta\n",
    "    This module differs from the built-in PyTorch BatchNorm2d as the mean and\n",
    "    standard-deviation are reduced across all devices during training.\n",
    "    For example, when one uses `nn.DataParallel` to wrap the network during\n",
    "    training, PyTorch's implementation normalize the tensor on each device using\n",
    "    the statistics only on that device, which accelerated the computation and\n",
    "    is also easy to implement, but the statistics might be inaccurate.\n",
    "    Instead, in this synchronized version, the statistics will be computed\n",
    "    over all training samples distributed on multiple devices.\n",
    "    Note that, for one-GPU or CPU-only case, this module behaves exactly same\n",
    "    as the built-in PyTorch implementation.\n",
    "    The mean and standard-deviation are calculated per-dimension over\n",
    "    the mini-batches and gamma and beta are learnable parameter vectors\n",
    "    of size C (where C is the input size).\n",
    "    During training, this layer keeps a running estimate of its computed mean\n",
    "    and variance. The running sum is kept with a default momentum of 0.1.\n",
    "    During evaluation, this running mean/variance is used for normalization.\n",
    "    Because the BatchNorm is done over the `C` dimension, computing statistics\n",
    "    on `(N, H, W)` slices, it's common terminology to call this Spatial BatchNorm\n",
    "    Args:\n",
    "        num_features: num_features from an expected input of\n",
    "            size batch_size x num_features x height x width\n",
    "        eps: a value added to the denominator for numerical stability.\n",
    "            Default: 1e-5\n",
    "        momentum: the value used for the running_mean and running_var\n",
    "            computation. Default: 0.1\n",
    "        affine: a boolean value that when set to ``True``, gives the layer learnable\n",
    "            affine parameters. Default: ``True``\n",
    "    Shape:\n",
    "        - Input: :math:`(N, C, H, W)`\n",
    "        - Output: :math:`(N, C, H, W)` (same shape as input)\n",
    "    Examples:\n",
    "        >>> # With Learnable Parameters\n",
    "        >>> m = SynchronizedBatchNorm2d(100)\n",
    "        >>> # Without Learnable Parameters\n",
    "        >>> m = SynchronizedBatchNorm2d(100, affine=False)\n",
    "        >>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45))\n",
    "        >>> output = m(input)\n",
    "    \"\"\"\n",
    "\n",
    "    def _check_input_dim(self, input):\n",
    "        if input.dim() != 4:\n",
    "            raise ValueError('expected 4D input (got {}D input)'\n",
    "                             .format(input.dim()))\n",
    "        super(SynchronizedBatchNorm2d, self)._check_input_dim(input)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" \n",
    "For handling DataParallel with Synchorisned Batch Norm.\n",
    "\"\"\"\n",
    "\n",
    "class CallbackContext(object):\n",
    "    pass\n",
    "\n",
    "class DataParallelWithCallback(DataParallel):\n",
    "    \"\"\"\n",
    "    Data Parallel with a replication callback.\n",
    "    An replication callback `__data_parallel_replicate__` of each module will be invoked after being created by\n",
    "    original `replicate` function.\n",
    "    The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)`\n",
    "    Examples:\n",
    "        > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)\n",
    "        > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])\n",
    "        # sync_bn.__data_parallel_replicate__ will be invoked.\n",
    "    \"\"\"\n",
    "\n",
    "    def replicate(self, module, device_ids):\n",
    "        modules = super(DataParallelWithCallback, self).replicate(module, device_ids)\n",
    "        execute_replication_callbacks(modules)\n",
    "        return modules\n",
    "\n",
    "\n",
    "def execute_replication_callbacks(modules):\n",
    "    \"\"\"\n",
    "    Execute an replication callback `__data_parallel_replicate__` on each module created by original replication.\n",
    "    The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)`\n",
    "    Note that, as all modules are isomorphism, we assign each sub-module with a context\n",
    "    (shared among multiple copies of this module on different devices).\n",
    "    Through this context, different copies can share some information.\n",
    "    We guarantee that the callback on the master copy (the first copy) will be called ahead of calling the callback\n",
    "    of any slave copies.\n",
    "    \"\"\"\n",
    "    master_copy = modules[0]\n",
    "    nr_modules = len(list(master_copy.modules()))\n",
    "    ctxs = [CallbackContext() for _ in range(nr_modules)]\n",
    "\n",
    "    for i, module in enumerate(modules):\n",
    "        for j, m in enumerate(module.modules()):\n",
    "            if hasattr(m, '__data_parallel_replicate__'):\n",
    "                m.__data_parallel_replicate__(ctxs[j], i)\n",
    "\n",
    "\n",
    "def patch_replication_callback(data_parallel):\n",
    "    \"\"\"\n",
    "    Monkey-patch an existing `DataParallel` object. Add the replication callback.\n",
    "    Useful when you have customized `DataParallel` implementation.\n",
    "    Examples:\n",
    "        > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)\n",
    "        > sync_bn = DataParallel(sync_bn, device_ids=[0, 1])\n",
    "        > patch_replication_callback(sync_bn)\n",
    "        # this is equivalent to\n",
    "        > sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)\n",
    "        > sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])\n",
    "    \"\"\"\n",
    "\n",
    "    assert isinstance(data_parallel, DataParallel)\n",
    "\n",
    "    old_replicate = data_parallel.replicate\n",
    "\n",
    "    @functools.wraps(old_replicate)\n",
    "    def new_replicate(module, device_ids):\n",
    "        modules = old_replicate(module, device_ids)\n",
    "        execute_replication_callbacks(modules)\n",
    "        return modules\n",
    "\n",
    "    data_parallel.replicate = new_replicate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**ResNet**\n",
    "Basic Implementation of ResNet models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Bottleneck(nn.Module):\n",
    "    expansion = 4\n",
    "\n",
    "    def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, BatchNorm=None):\n",
    "        super(Bottleneck, self).__init__()\n",
    "        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n",
    "        self.bn1 = BatchNorm(planes)\n",
    "        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n",
    "                               dilation=dilation, padding=dilation, bias=False)\n",
    "        self.bn2 = BatchNorm(planes)\n",
    "        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n",
    "        self.bn3 = BatchNorm(planes * 4)\n",
    "        self.relu = nn.ReLU(inplace=True)\n",
    "        self.downsample = downsample\n",
    "        self.stride = stride\n",
    "        self.dilation = dilation\n",
    "\n",
    "    def forward(self, x):\n",
    "        residual = x\n",
    "\n",
    "        out = self.conv1(x)\n",
    "        out = self.bn1(out)\n",
    "        out = self.relu(out)\n",
    "\n",
    "        out = self.conv2(out)\n",
    "        out = self.bn2(out)\n",
    "        out = self.relu(out)\n",
    "\n",
    "        out = self.conv3(out)\n",
    "        out = self.bn3(out)\n",
    "\n",
    "        if self.downsample is not None:\n",
    "            residual = self.downsample(x)\n",
    "\n",
    "        out += residual\n",
    "        out = self.relu(out)\n",
    "\n",
    "        return out\n",
    "\n",
    "class ResNet(nn.Module):\n",
    "\n",
    "    def __init__(self, block, layers, output_stride, BatchNorm, pretrained=True):\n",
    "        self.inplanes = 64\n",
    "        super(ResNet, self).__init__()\n",
    "        blocks = [1, 2, 4]\n",
    "        if output_stride == 16:\n",
    "            strides = [1, 2, 2, 1]\n",
    "            dilations = [1, 1, 1, 2]\n",
    "        elif output_stride == 8:\n",
    "            strides = [1, 2, 1, 1]\n",
    "            dilations = [1, 1, 2, 4]\n",
    "        else:\n",
    "            raise NotImplementedError\n",
    "\n",
    "        # Modules\n",
    "        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n",
    "                                bias=False)\n",
    "        self.bn1 = BatchNorm(64)\n",
    "        self.relu = nn.ReLU(inplace=True)\n",
    "        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n",
    "\n",
    "        self.layer1 = self._make_layer(block, 64, layers[0], stride=strides[0], dilation=dilations[0], BatchNorm=BatchNorm)\n",
    "        self.layer2 = self._make_layer(block, 128, layers[1], stride=strides[1], dilation=dilations[1], BatchNorm=BatchNorm)\n",
    "        self.layer3 = self._make_layer(block, 256, layers[2], stride=strides[2], dilation=dilations[2], BatchNorm=BatchNorm)\n",
    "        self.layer4 = self._make_MG_unit(block, 512, blocks=blocks, stride=strides[3], dilation=dilations[3], BatchNorm=BatchNorm)\n",
    "        # self.layer4 = self._make_layer(block, 512, layers[3], stride=strides[3], dilation=dilations[3], BatchNorm=BatchNorm)\n",
    "        self._init_weight()\n",
    "\n",
    "        if pretrained:\n",
    "            self._load_pretrained_model()\n",
    "\n",
    "    def _make_layer(self, block, planes, blocks, stride=1, dilation=1, BatchNorm=None):\n",
    "        downsample = None\n",
    "        if stride != 1 or self.inplanes != planes * block.expansion:\n",
    "            downsample = nn.Sequential(\n",
    "                nn.Conv2d(self.inplanes, planes * block.expansion,\n",
    "                          kernel_size=1, stride=stride, bias=False),\n",
    "                BatchNorm(planes * block.expansion),\n",
    "            )\n",
    "\n",
    "        layers = []\n",
    "        layers.append(block(self.inplanes, planes, stride, dilation, downsample, BatchNorm))\n",
    "        self.inplanes = planes * block.expansion\n",
    "        for i in range(1, blocks):\n",
    "            layers.append(block(self.inplanes, planes, dilation=dilation, BatchNorm=BatchNorm))\n",
    "\n",
    "        return nn.Sequential(*layers)\n",
    "\n",
    "    def _make_MG_unit(self, block, planes, blocks, stride=1, dilation=1, BatchNorm=None):\n",
    "        downsample = None\n",
    "        if stride != 1 or self.inplanes != planes * block.expansion:\n",
    "            downsample = nn.Sequential(\n",
    "                nn.Conv2d(self.inplanes, planes * block.expansion,\n",
    "                          kernel_size=1, stride=stride, bias=False),\n",
    "                BatchNorm(planes * block.expansion),\n",
    "            )\n",
    "\n",
    "        layers = []\n",
    "        layers.append(block(self.inplanes, planes, stride, dilation=blocks[0]*dilation,\n",
    "                            downsample=downsample, BatchNorm=BatchNorm))\n",
    "        self.inplanes = planes * block.expansion\n",
    "        for i in range(1, len(blocks)):\n",
    "            layers.append(block(self.inplanes, planes, stride=1,\n",
    "                                dilation=blocks[i]*dilation, BatchNorm=BatchNorm))\n",
    "\n",
    "        return nn.Sequential(*layers)\n",
    "\n",
    "    def forward(self, input):\n",
    "        x = self.conv1(input)\n",
    "        x = self.bn1(x)\n",
    "        x = self.relu(x)\n",
    "        x = self.maxpool(x)\n",
    "\n",
    "        x = self.layer1(x)\n",
    "        low_level_feat = x\n",
    "        x = self.layer2(x)\n",
    "        x = self.layer3(x)\n",
    "        x = self.layer4(x)\n",
    "        return x, low_level_feat\n",
    "\n",
    "    def _init_weight(self):\n",
    "        for m in self.modules():\n",
    "            if isinstance(m, nn.Conv2d):\n",
    "                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n",
    "                m.weight.data.normal_(0, math.sqrt(2. / n))\n",
    "            elif isinstance(m, SynchronizedBatchNorm2d):\n",
    "                m.weight.data.fill_(1)\n",
    "                m.bias.data.zero_()\n",
    "            elif isinstance(m, nn.BatchNorm2d):\n",
    "                m.weight.data.fill_(1)\n",
    "                m.bias.data.zero_()\n",
    "\n",
    "    def _load_pretrained_model(self):\n",
    "        pretrain_dict = model_zoo.load_url('https://download.pytorch.org/models/resnet101-5d3b4d8f.pth')\n",
    "        model_dict = {}\n",
    "        state_dict = self.state_dict()\n",
    "        for k, v in pretrain_dict.items():\n",
    "            if k in state_dict:\n",
    "                model_dict[k] = v\n",
    "        state_dict.update(model_dict)\n",
    "        self.load_state_dict(state_dict)\n",
    "\n",
    "def ResNet101(output_stride, BatchNorm, pretrained=True):\n",
    "    \"\"\"Constructs a ResNet-101 model.\n",
    "    Args:\n",
    "        pretrained (bool): If True, returns a model pre-trained on ImageNet\n",
    "    \"\"\"\n",
    "    model = ResNet(Bottleneck, [3, 4, 23, 3], output_stride, BatchNorm, pretrained=pretrained)\n",
    "    return model\n",
    "\n",
    "def ResNet50(output_stride, BatchNorm, pretrained=True):\n",
    "    \"\"\"Constructs a ResNet-101 model.\n",
    "    Args:\n",
    "        pretrained (bool): If True, returns a model pre-trained on ImageNet\n",
    "    \"\"\"\n",
    "    model = ResNet(Bottleneck, [3, 4, 6, 3], output_stride, BatchNorm, pretrained=pretrained)\n",
    "    return model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**FLOAT**\n",
    "Inspired from DeepLabV3+"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Backbone**\n",
    "Function returning ResNet backbone. Modifiable to use other backbones."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_backbone(backbone, output_stride, BatchNorm):\n",
    "    if backbone == 'resnet101':\n",
    "        return ResNet101(output_stride, BatchNorm)\n",
    "    elif backbone == 'resnet50':\n",
    "        return ResNet50(output_stride, BatchNorm)\n",
    "    else:\n",
    "        raise NotImplementedError"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**ASPP**\n",
    "Atrous Spatial Pyramid Pooling module from DeepLabV3+"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "class _ASPPModule(nn.Module):\n",
    "    def __init__(self, inplanes, planes, kernel_size, padding, dilation, BatchNorm):\n",
    "        super(_ASPPModule, self).__init__()\n",
    "        self.atrous_conv = nn.Conv2d(inplanes, planes, kernel_size=kernel_size,\n",
    "                                            stride=1, padding=padding, dilation=dilation, bias=False)\n",
    "        self.bn = BatchNorm(planes)\n",
    "        self.relu = nn.ReLU()\n",
    "\n",
    "        self._init_weight()\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = self.atrous_conv(x)\n",
    "        x = self.bn(x)\n",
    "\n",
    "        return self.relu(x)\n",
    "\n",
    "    def _init_weight(self):\n",
    "        for m in self.modules():\n",
    "            if isinstance(m, nn.Conv2d):\n",
    "                torch.nn.init.kaiming_normal_(m.weight)\n",
    "            elif isinstance(m, SynchronizedBatchNorm2d):\n",
    "                m.weight.data.fill_(1)\n",
    "                m.bias.data.zero_()\n",
    "            elif isinstance(m, nn.BatchNorm2d):\n",
    "                m.weight.data.fill_(1)\n",
    "                m.bias.data.zero_()\n",
    "\n",
    "class ASPP(nn.Module):\n",
    "    def __init__(self, backbone, output_stride, BatchNorm):\n",
    "        super(ASPP, self).__init__()\n",
    "        if backbone == 'drn':\n",
    "            inplanes = 512\n",
    "        elif backbone == 'mobilenet':\n",
    "            inplanes = 320\n",
    "        else:\n",
    "            inplanes = 2048\n",
    "        if output_stride == 16:\n",
    "            dilations = [1, 6, 12, 18]\n",
    "        elif output_stride == 8:\n",
    "            dilations = [1, 12, 24, 36]\n",
    "        else:\n",
    "            raise NotImplementedError\n",
    "\n",
    "        self.aspp1 = _ASPPModule(inplanes, 256, 1, padding=0, dilation=dilations[0], BatchNorm=BatchNorm)\n",
    "        self.aspp2 = _ASPPModule(inplanes, 256, 3, padding=dilations[1], dilation=dilations[1], BatchNorm=BatchNorm)\n",
    "        self.aspp3 = _ASPPModule(inplanes, 256, 3, padding=dilations[2], dilation=dilations[2], BatchNorm=BatchNorm)\n",
    "        self.aspp4 = _ASPPModule(inplanes, 256, 3, padding=dilations[3], dilation=dilations[3], BatchNorm=BatchNorm)\n",
    "\n",
    "        self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),\n",
    "                                             nn.Conv2d(inplanes, 256, 1, stride=1, bias=False),\n",
    "                                             BatchNorm(256),\n",
    "                                             nn.ReLU())\n",
    "        self.conv1 = nn.Conv2d(1280, 256, 1, bias=False)\n",
    "        self.bn1 = BatchNorm(256)\n",
    "        self.relu = nn.ReLU()\n",
    "        self.dropout = nn.Dropout(0.5)\n",
    "        self._init_weight()\n",
    "\n",
    "    def forward(self, x):\n",
    "        x1 = self.aspp1(x)\n",
    "        x2 = self.aspp2(x)\n",
    "        x3 = self.aspp3(x)\n",
    "        x4 = self.aspp4(x)\n",
    "        x5 = self.global_avg_pool(x)\n",
    "        x5 = F.interpolate(x5, size=x4.size()[2:], mode='bilinear', align_corners=True)\n",
    "        x = torch.cat((x1, x2, x3, x4, x5), dim=1)\n",
    "\n",
    "        x = self.conv1(x)\n",
    "        x = self.bn1(x)\n",
    "        x = self.relu(x)\n",
    "\n",
    "        return self.dropout(x)\n",
    "\n",
    "    def _init_weight(self):\n",
    "        for m in self.modules():\n",
    "            if isinstance(m, nn.Conv2d):\n",
    "                # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n",
    "                # m.weight.data.normal_(0, math.sqrt(2. / n))\n",
    "                torch.nn.init.kaiming_normal_(m.weight)\n",
    "            elif isinstance(m, SynchronizedBatchNorm2d):\n",
    "                m.weight.data.fill_(1)\n",
    "                m.bias.data.zero_()\n",
    "            elif isinstance(m, nn.BatchNorm2d):\n",
    "                m.weight.data.fill_(1)\n",
    "                m.bias.data.zero_()\n",
    "\n",
    "\n",
    "def build_aspp(backbone, output_stride, BatchNorm):\n",
    "    return ASPP(backbone, output_stride, BatchNorm)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Decoder**\n",
    "Decoder from DeepLabV3+"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Decoder(nn.Module):\n",
    "    def __init__(self, num_classes, backbone, BatchNorm):\n",
    "        super(Decoder, self).__init__()\n",
    "        if backbone == 'resnet101' or backbone == 'resnet50' or backbone == 'drn':\n",
    "            low_level_inplanes = 256\n",
    "        elif backbone == 'xception':\n",
    "            low_level_inplanes = 128\n",
    "        elif backbone == 'mobilenet':\n",
    "            low_level_inplanes = 24\n",
    "        else:\n",
    "            raise NotImplementedError\n",
    "\n",
    "        self.conv1 = nn.Conv2d(low_level_inplanes, 48, 1, bias=False)\n",
    "        self.bn1 = BatchNorm(48)\n",
    "        self.relu = nn.ReLU()\n",
    "        self.last_conv = nn.Sequential(nn.Conv2d(304, 256, kernel_size=3, stride=1, padding=1, bias=False),\n",
    "                                       BatchNorm(256),\n",
    "                                       nn.ReLU(),\n",
    "                                       nn.Dropout(0.5),\n",
    "                                       nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1, bias=False),\n",
    "                                       BatchNorm(256),\n",
    "                                       nn.ReLU(),\n",
    "                                       nn.Dropout(0.1),\n",
    "                                       nn.Conv2d(256, num_classes, kernel_size=1, stride=1))\n",
    "        self._init_weight()\n",
    "\n",
    "\n",
    "    def forward(self, x, low_level_feat):\n",
    "        low_level_feat = self.conv1(low_level_feat)\n",
    "        low_level_feat = self.bn1(low_level_feat)\n",
    "        low_level_feat = self.relu(low_level_feat)\n",
    "\n",
    "        x = F.interpolate(x, size=low_level_feat.size()[2:], mode='bilinear', align_corners=True)\n",
    "        x = torch.cat((x, low_level_feat), dim=1)\n",
    "        x = self.last_conv(x)\n",
    "\n",
    "        return x\n",
    "\n",
    "    def _init_weight(self):\n",
    "        for m in self.modules():\n",
    "            if isinstance(m, nn.Conv2d):\n",
    "                torch.nn.init.kaiming_normal_(m.weight)\n",
    "            elif isinstance(m, SynchronizedBatchNorm2d):\n",
    "                m.weight.data.fill_(1)\n",
    "                m.bias.data.zero_()\n",
    "            elif isinstance(m, nn.BatchNorm2d):\n",
    "                m.weight.data.fill_(1)\n",
    "                m.bias.data.zero_()\n",
    "\n",
    "def build_decoder(num_classes, backbone, BatchNorm):\n",
    "    return Decoder(num_classes, backbone, BatchNorm)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Float**\n",
    "Using DeepLabV3+'s modules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Float(nn.Module):\n",
    "    def __init__(self, num_anim_classes, num_inanim_classes, backbone='resnet101', output_stride=16,\n",
    "                 sync_bn=True, freeze_bn=False):\n",
    "        super(Float, self).__init__()\n",
    "        if backbone == 'drn':\n",
    "            output_stride = 8\n",
    "\n",
    "        if sync_bn == True:\n",
    "            BatchNorm = SynchronizedBatchNorm2d\n",
    "        else:\n",
    "            BatchNorm = nn.BatchNorm2d\n",
    "\n",
    "        self.backbone = build_backbone(backbone, output_stride, BatchNorm)\n",
    "\n",
    "        self.anim_aspp = build_aspp(backbone, output_stride, BatchNorm)\n",
    "        self.anim_decoder = build_decoder(num_anim_classes, backbone, BatchNorm)\n",
    "\n",
    "        self.inanim_aspp = build_aspp(backbone, output_stride, BatchNorm)\n",
    "        self.inanim_decoder = build_decoder(num_inanim_classes, backbone, BatchNorm)\n",
    "\n",
    "        self.lrfb_aspp = build_aspp(backbone, output_stride, BatchNorm)\n",
    "        self.lr_decoder = build_decoder(3, backbone, BatchNorm)\n",
    "        self.fb_decoder = build_decoder(3, backbone, BatchNorm)\n",
    "\n",
    "        self.freeze_bn = freeze_bn\n",
    "\n",
    "    def forward(self, input):\n",
    "        x, low_level_feat = self.backbone(input)\n",
    "        anim_x = self.anim_aspp(x)\n",
    "        anim_x = self.anim_decoder(anim_x, low_level_feat)\n",
    "        anim_x = F.interpolate(anim_x, size=input.size()[2:], mode='bilinear', align_corners=True)\n",
    "\n",
    "        inanim_x = self.inanim_aspp(x)\n",
    "        inanim_x = self.inanim_decoder(inanim_x, low_level_feat)\n",
    "        inanim_x = F.interpolate(inanim_x, size=input.size()[2:], mode='bilinear', align_corners=True)\n",
    "\n",
    "        lrfb_x = self.lrfb_aspp(x)\n",
    "        lr = self.lr_decoder(lrfb_x, low_level_feat)\n",
    "        lr = F.interpolate(lr, size=input.size()[2:], mode='bilinear', align_corners=True)\n",
    "\n",
    "        fb = self.fb_decoder(lrfb_x, low_level_feat)\n",
    "        fb = F.interpolate(fb, size=input.size()[2:], mode='bilinear', align_corners=True)            \n",
    "        return anim_x, inanim_x, lr, fb\n",
    "\n",
    "    def freeze_bn(self):\n",
    "        for m in self.modules():\n",
    "            if isinstance(m, SynchronizedBatchNorm2d):\n",
    "                m.eval()\n",
    "            elif isinstance(m, nn.BatchNorm2d):\n",
    "                m.eval()\n",
    "\n",
    "    def get_1x_lr_params(self):\n",
    "        modules = [self.backbone]\n",
    "        for i in range(len(modules)):\n",
    "            for m in modules[i].named_modules():\n",
    "                if self.freeze_bn:\n",
    "                    if isinstance(m[1], nn.Conv2d):\n",
    "                        for p in m[1].parameters():\n",
    "                            if p.requires_grad:\n",
    "                                yield p\n",
    "                else:\n",
    "                    if isinstance(m[1], nn.Conv2d) or isinstance(m[1], SynchronizedBatchNorm2d) \\\n",
    "                            or isinstance(m[1], nn.BatchNorm2d):\n",
    "                        for p in m[1].parameters():\n",
    "                            if p.requires_grad:\n",
    "                                yield p\n",
    "\n",
    "    def get_10x_lr_params(self):\n",
    "        modules = [self.anim_aspp, self.inanim_aspp, self.lrfb_aspp, self.anim_decoder,\n",
    "                   self.inanim_decoder, self.lr_decoder, self.fb_decoder]\n",
    "        for i in range(len(modules)):\n",
    "            for m in modules[i].named_modules():\n",
    "                if self.freeze_bn:\n",
    "                    if isinstance(m[1], nn.Conv2d):\n",
    "                        for p in m[1].parameters():\n",
    "                            if p.requires_grad:\n",
    "                                yield p\n",
    "                else:\n",
    "                    if isinstance(m[1], nn.Conv2d) or isinstance(m[1], SynchronizedBatchNorm2d) \\\n",
    "                            or isinstance(m[1], nn.BatchNorm2d):\n",
    "                        for p in m[1].parameters():\n",
    "                            if p.requires_grad:\n",
    "                                yield p"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Metric calculator functions**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "class AverageMeter(object):\n",
    "    \"\"\"Used for updatable average loss computation.\"\"\"\n",
    "    def __init__(self):\n",
    "        self.reset()\n",
    "\n",
    "    def reset(self):\n",
    "        self.val = 0\n",
    "        self.avg = 0\n",
    "        self.sum = 0\n",
    "        self.count = 0\n",
    "\n",
    "    def update(self, val, n=1):\n",
    "        self.val = val\n",
    "        self.sum += val * n\n",
    "        self.count += n\n",
    "        self.avg = self.sum / self.count"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "class sqIOUMeter(object):\n",
    "    \"\"\"Used for updatable sqIOU style average (per class) calcuation.\"\"\"\n",
    "    def __init__(self, n_classes):\n",
    "        self.n_classes = n_classes\n",
    "        self.vals = {}\n",
    "        self.counts = {}\n",
    "        for i in range(self.n_classes):\n",
    "            self.vals[i] = 0\n",
    "            self.counts[i] = 0\n",
    "\n",
    "    def update(self, val_d, count_d):\n",
    "        sqiou = []\n",
    "        for i in range(self.n_classes):\n",
    "            self.vals[i] += val_d[i]\n",
    "            self.counts[i] += count_d[i]\n",
    "            if self.counts[i] > 0:\n",
    "                sqiou.append(self.vals[i] / self.counts[i])\n",
    "\n",
    "        self.avg = np.mean(sqiou)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Used for updatated mIOU calcuation among other metrics.\"\"\"\n",
    "class Evaluator(object):\n",
    "    def __init__(self, num_class):\n",
    "        self.num_class = num_class\n",
    "        self.confusion_matrix = np.zeros((self.num_class,)*2)\n",
    "        \n",
    "    def set_confusion_matrix(self, conf_mat):\n",
    "        self.confusion_matrix = np.copy(conf_mat)\n",
    "\n",
    "    def Pixel_Accuracy(self):\n",
    "        Acc = np.diag(self.confusion_matrix).sum() / self.confusion_matrix.sum()\n",
    "        return Acc\n",
    "\n",
    "    def Pixel_Accuracy_Class(self):\n",
    "        Acc = np.diag(self.confusion_matrix) / self.confusion_matrix.sum(axis=1)\n",
    "        Acc = np.nanmean(Acc)\n",
    "        return Acc\n",
    "\n",
    "    def Mean_Intersection_over_Union(self):\n",
    "        MIoU = np.diag(self.confusion_matrix) / (\n",
    "                    np.sum(self.confusion_matrix, axis=1) + np.sum(self.confusion_matrix, axis=0) -\n",
    "                    np.diag(self.confusion_matrix))\n",
    "        MIoU = np.nanmean(MIoU)\n",
    "        return MIoU\n",
    "    \n",
    "    def Mean_Intersection_over_Union_PerClass(self):\n",
    "        MIoU = np.diag(self.confusion_matrix) / (\n",
    "                    np.sum(self.confusion_matrix, axis=1) + np.sum(self.confusion_matrix, axis=0) -\n",
    "                    np.diag(self.confusion_matrix))\n",
    "        return MIoU\n",
    "\n",
    "    def Frequency_Weighted_Intersection_over_Union(self):\n",
    "        freq = np.sum(self.confusion_matrix, axis=1) / np.sum(self.confusion_matrix)\n",
    "        iu = np.diag(self.confusion_matrix) / (\n",
    "                    np.sum(self.confusion_matrix, axis=1) + np.sum(self.confusion_matrix, axis=0) -\n",
    "                    np.diag(self.confusion_matrix))\n",
    "\n",
    "        FWIoU = (freq[freq > 0] * iu[freq > 0]).sum()\n",
    "        return FWIoU\n",
    "\n",
    "    def _generate_matrix(self, gt_image, pre_image):\n",
    "        mask = (gt_image >= 0) & (gt_image < self.num_class)\n",
    "        label = self.num_class * gt_image[mask].astype('int') + pre_image[mask]\n",
    "        count = np.bincount(label, minlength=self.num_class**2)\n",
    "        confusion_matrix = count.reshape(self.num_class, self.num_class)\n",
    "        return confusion_matrix\n",
    "\n",
    "    def add_batch(self, gt_image, pre_image):\n",
    "        assert gt_image.shape == pre_image.shape\n",
    "        self.confusion_matrix += self._generate_matrix(gt_image, pre_image)\n",
    "\n",
    "    def reset(self):\n",
    "        self.confusion_matrix = np.zeros((self.num_class,) * 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Returns the per class mIOU and per class count in a batch.\n",
    "\"\"\"\n",
    "def jaccard_perpart(y_pred, y_true, num_classes):\n",
    "    num_parts = y_pred.shape[1]\n",
    "    y_pred = torch.argmax(y_pred, 1)\n",
    "    y_pred = y_pred.type(torch.LongTensor)\n",
    "    y_true = y_true.type(torch.LongTensor)\n",
    "    y_pred = F.one_hot(y_pred, num_classes=num_classes)\n",
    "    y_true = F.one_hot(y_true, num_classes=num_classes)\n",
    "    nbs = y_pred.shape[0]\n",
    "    ious = {}\n",
    "    counts = {}\n",
    "    for i in range(num_parts):\n",
    "        pred = y_pred[:,:,:,i]\n",
    "        gt = y_true[:,:,:,i]\n",
    "        inter = torch.logical_and(pred, gt)\n",
    "        union = torch.logical_or(pred, gt)\n",
    "        iou = torch.sum(inter, [1,2]) / torch.sum(union, [1,2])\n",
    "        legal = torch.sum(gt, [1,2]) > 0\n",
    "        ious[i] = torch.sum(iou[legal])\n",
    "        counts[i] = torch.sum(legal)\n",
    "\n",
    "    return ious, counts\n",
    "\n",
    "\"\"\"\n",
    "Returns the per class 'intersection over ground truth' and per class count in a batch.\n",
    "\"\"\"\n",
    "def iogt_perpart(y_pred, y_true, num_classes):\n",
    "    num_parts = y_pred.shape[1]\n",
    "    y_pred = torch.argmax(y_pred, 1)\n",
    "    y_pred = y_pred.type(torch.LongTensor)\n",
    "    y_true = y_true.type(torch.LongTensor)\n",
    "    y_pred = F.one_hot(y_pred, num_classes=num_classes)\n",
    "    y_true = F.one_hot(y_true, num_classes=num_classes)\n",
    "    nbs = y_pred.shape[0]\n",
    "    iogts = {}\n",
    "    counts = {}\n",
    "    for i in range(1, num_parts):\n",
    "        pred = y_pred[:,:,:,i]\n",
    "        gt = y_true[:,:,:,i]\n",
    "        inter = torch.logical_and(pred, gt)\n",
    "        iogt = torch.sum(inter, [1,2]) / torch.sum(gt, [1,2])\n",
    "        legal = torch.sum(gt, [1,2]) > 0\n",
    "        iogts[i-1] = torch.sum(iogt[legal])\n",
    "        counts[i-1] = torch.sum(legal)\n",
    "\n",
    "    return iogts, counts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Losses**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Dilated mask computation for adjacent graph loss.\n",
    "\"\"\"\n",
    "def compute_dilated_mask(image, class_index, dilation_kernel, ignore_label=None):\n",
    "    # Mask of the specific class\n",
    "    mask = torch.eq(image, class_index).float()\n",
    "\n",
    "    if ignore_label is not None:\n",
    "        mask_ignore = 1.0 - torch.eq(image, ignore_label).float()\n",
    "        mask = tf.multiply(mask_ignore, mask)\n",
    "\n",
    "    dilated_mask = nn.MaxPool2d(kernel_size=dilation_kernel, stride=1, padding=1)(mask)\n",
    "\n",
    "    return dilated_mask"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Returns adjacency matrix for graph loss computation.\n",
    "The adjacency matrix contains how many pixels overlap after dilation for a pair of parts.\n",
    "\"\"\"\n",
    "def compute_adj_mat(image, adj_mat, num_classes, present_classes, ignore_label, dilation_kernel, weighted):\n",
    "\n",
    "    num_present_classes = present_classes.shape[0]\n",
    "    i = 1\n",
    "\n",
    "    while (i < num_present_classes):\n",
    "        j = i + 1\n",
    "\n",
    "        first_dilated_mask = compute_dilated_mask(image, present_classes[i], dilation_kernel)\n",
    "\n",
    "        while (j < num_present_classes):\n",
    "            second_dilated_mask = compute_dilated_mask(image, present_classes[j], dilation_kernel)\n",
    "\n",
    "            intersection = torch.mul(first_dilated_mask, second_dilated_mask)\n",
    "\n",
    "            adjacent_pixels = torch.sum(intersection).type(torch.int)\n",
    "\n",
    "            # WeightedAdjMat - The class1-class2 value contains the number of adjacent pixels if the 2 classes\n",
    "            # are adjacent,  0 otherwise\n",
    "            if weighted:\n",
    "                indices = torch.Tensor([[present_classes[i]], [present_classes[j]], [0]])\n",
    "                values = torch.reshape(adjacent_pixels, [1]).cpu()\n",
    "                shape = [num_classes, num_classes, 1]\n",
    "                delta = torch.sparse_coo_tensor(indices, values, shape)\n",
    "                adj_mat = adj_mat + delta.to_dense()\n",
    "\n",
    "            # SimpleAdjMat - The class1-class2 value contains 1 if the 2 classes are adjacent, 0 otherwise\n",
    "            else:\n",
    "                value = adjacent_pixels > 0\n",
    "                value = value.float()\n",
    "                indices = torch.Tensor([[present_classes[i], present_classes[j], 0]])\n",
    "                values = torch.reshape(value, [1])\n",
    "                shape = [num_classes, num_classes, 1]\n",
    "                delta = torch.sparse_coo_tensor(indices, values, shape)\n",
    "                adj_mat = adj_mat + delta.to_dense()\n",
    "\n",
    "            j = j + 1\n",
    "\n",
    "        \n",
    "        i = i + 1\n",
    "\n",
    "    return adj_mat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Computes and retunrs the graph loss. MSE Loss between the graph from the prediction vs the ground truth.\n",
    "\"\"\"\n",
    "def adjacent_graph_loss(pred, gt, num_classes, weighted=True,\n",
    "                        ignore_label=None, lambda_loss=0.1,\n",
    "                        dilation_kernel=3):\n",
    "    pred = F.interpolate(pred, size=gt.shape[1:], mode='bilinear', align_corners=False)\n",
    "    pred = torch.argmax(pred, dim=1)\n",
    "    \n",
    "    concat = torch.cat([torch.reshape(pred, [-1]), torch.reshape(gt, [-1])], 0)\n",
    "    unique = torch.unique(concat, sorted=True)\n",
    "    \n",
    "    logits_adj_mat = torch.zeros([num_classes, num_classes, 1], dtype=torch.int32)\n",
    "    labels_adj_mat = torch.zeros([num_classes, num_classes, 1], dtype=torch.int32)\n",
    "    \n",
    "    logits_adj_mat = compute_adj_mat(image=pred,\n",
    "                                     adj_mat=logits_adj_mat,\n",
    "                                     num_classes=num_classes,\n",
    "                                     present_classes=unique,\n",
    "                                     ignore_label=ignore_label,\n",
    "                                     dilation_kernel=dilation_kernel,\n",
    "                                     weighted=weighted)\n",
    "\n",
    "    labels_adj_mat = compute_adj_mat(image=gt,\n",
    "                                     adj_mat=labels_adj_mat,\n",
    "                                     num_classes=num_classes,\n",
    "                                     present_classes=unique,\n",
    "                                     ignore_label=ignore_label,\n",
    "                                     dilation_kernel=dilation_kernel,\n",
    "                                     weighted=weighted)\n",
    "    \n",
    "    logits_adj_mat = logits_adj_mat.type(torch.DoubleTensor)\n",
    "    labels_adj_mat = labels_adj_mat.type(torch.DoubleTensor)\n",
    "    if weighted:\n",
    "        logits_adj_mat = F.normalize(logits_adj_mat, dim=0)\n",
    "        labels_adj_mat = F.normalize(labels_adj_mat, dim=0)\n",
    "        \n",
    "    loss = nn.MSELoss()(logits_adj_mat, labels_adj_mat)\n",
    "    return loss * lambda_loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Loss forcing all parts to belong to an object.\n",
    "\"\"\"\n",
    "def objmask_loss(pred, macro_gt, num_classes, weighted=True,\n",
    "                 ignore_label=None, lambda_loss=0.001,\n",
    "                 dilation_kernel=3, label_weights=None):\n",
    "    pred = F.interpolate(pred, size=macro_gt.shape[1:], mode='bilinear', align_corners=False)\n",
    "\n",
    "    macro_class_logits = torch.split(pred, [1, num_classes-1], dim=1)\n",
    "    macro_logits_sum = []\n",
    "    for i in range(len(macro_class_logits)):\n",
    "            macro_logits_sum.append(torch.sum(macro_class_logits[i], axis=1))\n",
    "    \n",
    "    macro_pred = torch.stack(macro_logits_sum, axis=1)\n",
    "    loss = nn.CrossEntropyLoss(weight=label_weights)(macro_pred, macro_gt)\n",
    "    return loss * lambda_loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Standard crossentropy loss between prediction and ground truth.\n",
    "\"\"\"\n",
    "def crossentropy_loss(pred, gt, lambda_loss=1.0, label_weights=None):\n",
    "    pred = F.interpolate(pred, size=gt.shape[1:], mode='bilinear', align_corners=False)\n",
    "\n",
    "    loss = nn.CrossEntropyLoss(weight=label_weights)(pred, gt)\n",
    "    return loss * lambda_loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Mapping from object category label and factored part label to original dataset label category.\n",
    "\"\"\"\n",
    "def aggregate_parts_to_classes(num_classes=201, animate=True):\n",
    "\n",
    "    # Animate parts : Head(1), Torso(2), Leg(3), Tail(4), Wing(5), Lower Arm(6), Neck(7),\n",
    "    #                 Eye(8), Ear(9), Nose(10), Muzzle(11), Horn(12), Mouth(13),\n",
    "    #                 Hair(14), Foot(15), Hand(16), Paw(17), Hoof(18), Beak(19), Eyebrow(20),\n",
    "    #                 Lower Leg (21), Upper Leg (22), Upper Arm (23)\n",
    "\n",
    "    map_pc = {}\n",
    "    for i in range(num_classes):\n",
    "        map_pc[i] = 0\n",
    "\n",
    "    if animate:\n",
    "        map_pc[15] = 19  # Bird\n",
    "        map_pc[16] = 1\n",
    "        map_pc[17] = 8\n",
    "        map_pc[18] = 15\n",
    "        map_pc[19] = 3\n",
    "        map_pc[20] = 5\n",
    "        map_pc[21] = 7\n",
    "        map_pc[22] = 8\n",
    "        map_pc[23] = 15\n",
    "        map_pc[24] = 3\n",
    "        map_pc[25] = 5\n",
    "        map_pc[26] = 4\n",
    "        map_pc[27] = 2\n",
    "\n",
    "        map_pc[57] = 1  # Cat\n",
    "        map_pc[58] = 3\n",
    "        map_pc[59] = 17\n",
    "        map_pc[60] = 9\n",
    "        map_pc[61] = 8\n",
    "        map_pc[62] = 3\n",
    "        map_pc[63] = 17\n",
    "        map_pc[64] = 7\n",
    "        map_pc[65] = 10\n",
    "        map_pc[66] = 3\n",
    "        map_pc[67] = 17\n",
    "        map_pc[68] = 9\n",
    "        map_pc[69] = 8\n",
    "        map_pc[70] = 3\n",
    "        map_pc[71] = 17\n",
    "        map_pc[72] = 4\n",
    "        map_pc[73] = 2\n",
    "\n",
    "        map_pc[75] = 1  # Cow\n",
    "        map_pc[76] = 21\n",
    "        map_pc[77] = 22\n",
    "        map_pc[78] = 9\n",
    "        map_pc[79] = 8\n",
    "        map_pc[80] = 21\n",
    "        map_pc[81] = 22\n",
    "        map_pc[82] = 12\n",
    "        map_pc[83] = 11\n",
    "        map_pc[84] = 7\n",
    "        map_pc[85] = 21\n",
    "        map_pc[86] = 22\n",
    "        map_pc[87] = 9\n",
    "        map_pc[88] = 8\n",
    "        map_pc[89] = 21\n",
    "        map_pc[90] = 22\n",
    "        map_pc[91] = 12\n",
    "        map_pc[92] = 4\n",
    "        map_pc[93] = 2\n",
    "\n",
    "        map_pc[95] = 1  # Dog\n",
    "        map_pc[96] = 3\n",
    "        map_pc[97] = 17\n",
    "        map_pc[98] = 9\n",
    "        map_pc[99] = 8\n",
    "        map_pc[100] = 3\n",
    "        map_pc[101] = 17\n",
    "        map_pc[102] = 11\n",
    "        map_pc[103] = 7\n",
    "        map_pc[104] = 10\n",
    "        map_pc[105] = 3\n",
    "        map_pc[106] = 17\n",
    "        map_pc[107] = 9\n",
    "        map_pc[108] = 8\n",
    "        map_pc[109] = 3\n",
    "        map_pc[110] = 17\n",
    "        map_pc[111] = 4\n",
    "        map_pc[112] = 2\n",
    "\n",
    "        map_pc[113] = 1  # Horse\n",
    "        map_pc[114] = 18\n",
    "        map_pc[115] = 21\n",
    "        map_pc[116] = 22\n",
    "        map_pc[117] = 9\n",
    "        map_pc[118] = 8\n",
    "        map_pc[119] = 18\n",
    "        map_pc[120] = 21\n",
    "        map_pc[121] = 22\n",
    "        map_pc[122] = 11\n",
    "        map_pc[123] = 7\n",
    "        map_pc[124] = 18\n",
    "        map_pc[125] = 21\n",
    "        map_pc[126] = 22\n",
    "        map_pc[127] = 9\n",
    "        map_pc[128] = 8\n",
    "        map_pc[129] = 18\n",
    "        map_pc[130] = 21\n",
    "        map_pc[131] = 22\n",
    "        map_pc[132] = 4\n",
    "        map_pc[133] = 2\n",
    "\n",
    "        map_pc[140] = 14  # Person\n",
    "        map_pc[141] = 1\n",
    "        map_pc[142] = 9\n",
    "        map_pc[143] = 8\n",
    "        map_pc[144] = 20\n",
    "        map_pc[145] = 15\n",
    "        map_pc[146] = 16\n",
    "        map_pc[147] = 6\n",
    "        map_pc[148] = 21\n",
    "        map_pc[149] = 23\n",
    "        map_pc[150] = 22\n",
    "        map_pc[151] = 13\n",
    "        map_pc[152] = 7\n",
    "        map_pc[153] = 10\n",
    "        map_pc[154] = 9\n",
    "        map_pc[155] = 8\n",
    "        map_pc[156] = 20\n",
    "        map_pc[157] = 15\n",
    "        map_pc[158] = 16\n",
    "        map_pc[159] = 6\n",
    "        map_pc[160] = 21\n",
    "        map_pc[161] = 23\n",
    "        map_pc[162] = 22\n",
    "        map_pc[163] = 2\n",
    "\n",
    "        map_pc[166] = 1  # Sheep\n",
    "        map_pc[167] = 21\n",
    "        map_pc[168] = 22\n",
    "        map_pc[169] = 9\n",
    "        map_pc[170] = 8\n",
    "        map_pc[171] = 21\n",
    "        map_pc[172] = 22\n",
    "        map_pc[173] = 12\n",
    "        map_pc[174] = 11\n",
    "        map_pc[175] = 7\n",
    "        map_pc[176] = 21\n",
    "        map_pc[177] = 22\n",
    "        map_pc[178] = 9\n",
    "        map_pc[179] = 8\n",
    "        map_pc[180] = 21\n",
    "        map_pc[181] = 22\n",
    "        map_pc[182] = 12\n",
    "        map_pc[183] = 4\n",
    "        map_pc[184] = 2\n",
    "        \n",
    "    # Inanimate parts : Body (1), Wheel (2), Wing (3), Stern (4), Engine(5), Light (6),\n",
    "    #                   Plate (7), Screen (8), Pot (9), Plant (10), Window (11), Bottle Body (12),\n",
    "    #                   Bottle Cap (13), Saddle (14), Handlebar(15), Chainwheel (16), Side (17),\n",
    "    #                   Roof (18), Mirror (19), Door (20), Head (21), Head Side (22), Head Roof (23),\n",
    "    #                   Coach(24), Coach Side (25), Coach Roof (26), TV Frame (27), Tail (28)\n",
    "        \n",
    "    else:\n",
    "        map_pc[1] = 1  # Aeroplane\n",
    "        map_pc[2] = 5\n",
    "        map_pc[3] = 3\n",
    "        map_pc[4] = 3\n",
    "        map_pc[5] = 4\n",
    "        map_pc[6] = 28\n",
    "        map_pc[7] = 2\n",
    "\n",
    "        map_pc[8] = 2 # Bicycle\n",
    "        map_pc[9] = 16\n",
    "        map_pc[10] = 1\n",
    "        map_pc[11] = 2\n",
    "        map_pc[12] = 15\n",
    "        map_pc[13] = 6\n",
    "        map_pc[14] = 14\n",
    "\n",
    "        map_pc[29] = 12 # Bottle\n",
    "        map_pc[30] = 13\n",
    "\n",
    "        map_pc[31] = 7 # Bus\n",
    "        map_pc[32] = 17\n",
    "        map_pc[33] = 20\n",
    "        map_pc[34] = 7\n",
    "        map_pc[35] = 17\n",
    "        map_pc[36] = 6\n",
    "        map_pc[37] = 19\n",
    "        map_pc[38] = 17\n",
    "        map_pc[39] = 19\n",
    "        map_pc[40] = 17\n",
    "        map_pc[41] = 18\n",
    "        map_pc[42] = 2\n",
    "        map_pc[43] = 11\n",
    "\n",
    "        map_pc[44] = 7 # Car\n",
    "        map_pc[45] = 17\n",
    "        map_pc[46] = 20\n",
    "        map_pc[47] = 7\n",
    "        map_pc[48] = 17\n",
    "        map_pc[49] = 6\n",
    "        map_pc[50] = 19\n",
    "        map_pc[51] = 17\n",
    "        map_pc[52] = 19\n",
    "        map_pc[53] = 17\n",
    "        map_pc[54] = 18\n",
    "        map_pc[55] = 2\n",
    "        map_pc[56] = 11\n",
    "\n",
    "        map_pc[134] = 2 # Motorbike\n",
    "        map_pc[135] = 1\n",
    "        map_pc[136] = 2\n",
    "        map_pc[137] = 15\n",
    "        map_pc[138] = 6\n",
    "        map_pc[139] = 14\n",
    "\n",
    "        map_pc[164] = 10 # Potted plant\n",
    "        map_pc[165] = 9\n",
    "        \n",
    "        map_pc[186] = 25 # Train\n",
    "        map_pc[187] = 25\n",
    "        map_pc[188] = 25\n",
    "        map_pc[189] = 25\n",
    "        map_pc[190] = 26\n",
    "        map_pc[191] = 24\n",
    "        map_pc[192] = 21\n",
    "        map_pc[193] = 22\n",
    "        map_pc[194] = 22\n",
    "        map_pc[195] = 22\n",
    "        map_pc[196] = 22\n",
    "        map_pc[197] = 23\n",
    "        map_pc[198] = 6\n",
    "\n",
    "        map_pc[199] = 27 # Tv monitor\n",
    "        map_pc[200] = 8\n",
    "\n",
    "    return map_pc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Basic image and label transforms for the dataset.\n",
    "\"\"\"\n",
    "from PIL import Image, ImageOps, ImageFilter\n",
    "from torchvision import transforms\n",
    "\n",
    "class Normalize(object):\n",
    "    \"\"\"Normalize a tensor image with mean and standard deviation.\n",
    "    Args:\n",
    "        mean (tuple): means for each channel.\n",
    "        std (tuple): standard deviations for each channel.\n",
    "    \"\"\"\n",
    "    def __init__(self, mean=(0., 0., 0.), std=(1., 1., 1.)):\n",
    "        self.mean = mean\n",
    "        self.std = std\n",
    "\n",
    "    def __call__(self, sample):\n",
    "        img = sample['image']\n",
    "        anim_obj = sample['anim_obj']\n",
    "        inanim_obj = sample['inanim_obj']\n",
    "        anim = sample['anim']\n",
    "        inanim = sample['inanim']\n",
    "        adj1 = sample['adj1']\n",
    "        adj2 = sample['adj2']\n",
    "        adj1_o = sample['adj1_o']\n",
    "        adj2_o = sample['adj2_o']\n",
    "\n",
    "        img = np.array(img).astype(np.float32)\n",
    "        anim_obj = np.array(anim_obj).astype(np.float32)\n",
    "        inanim_obj = np.array(inanim_obj).astype(np.float32)\n",
    "        anim = np.array(anim).astype(np.float32)\n",
    "        inanim = np.array(inanim).astype(np.float32)\n",
    "        adj1 = np.array(adj1).astype(np.float32)\n",
    "        adj2 = np.array(adj2).astype(np.float32)\n",
    "        adj1_o = np.array(adj1_o).astype(np.float32)\n",
    "        adj2_o = np.array(adj2_o).astype(np.float32)\n",
    "        img /= 255.0\n",
    "        img -= self.mean\n",
    "        img /= self.std\n",
    "\n",
    "        return {'image': img,\n",
    "                'anim_obj': anim_obj,\n",
    "                'inanim_obj': inanim_obj,\n",
    "                'anim': anim,\n",
    "                'inanim': inanim,\n",
    "                'adj1':adj1,\n",
    "                'adj2':adj2,\n",
    "                'adj1_o':adj1_o,\n",
    "                'adj2_o':adj2_o}\n",
    "\n",
    "\n",
    "class ToTensor(object):\n",
    "    \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n",
    "\n",
    "    def __call__(self, sample):\n",
    "        # swap color axis because\n",
    "        # numpy image: H x W x C\n",
    "        # torch image: C X H X W\n",
    "        img = sample['image']\n",
    "        anim_obj = sample['anim_obj']\n",
    "        inanim_obj = sample['inanim_obj']\n",
    "        anim = sample['anim']\n",
    "        inanim = sample['inanim']\n",
    "        adj1 = sample['adj1']\n",
    "        adj2 = sample['adj2']\n",
    "        adj1_o = sample['adj1_o']\n",
    "        adj2_o = sample['adj2_o']\n",
    "\n",
    "        img = np.array(img).astype(np.float32).transpose((2, 0, 1))\n",
    "        anim_obj = np.array(anim_obj).astype(np.float32)\n",
    "        inanim_obj = np.array(inanim_obj).astype(np.float32)\n",
    "        anim = np.array(anim).astype(np.float32)\n",
    "        inanim = np.array(inanim).astype(np.float32)\n",
    "        adj1 = np.array(adj1).astype(np.float32)\n",
    "        adj2 = np.array(adj2).astype(np.float32)\n",
    "        adj1_o = np.array(adj1_o).astype(np.float32)\n",
    "        adj2_o = np.array(adj2_o).astype(np.float32)\n",
    "\n",
    "        img = torch.from_numpy(img).float()\n",
    "        anim_obj = torch.from_numpy(anim_obj).float()\n",
    "        inanim_obj = torch.from_numpy(inanim_obj).float()\n",
    "        anim = torch.from_numpy(anim).float()\n",
    "        inanim = torch.from_numpy(inanim).float()\n",
    "        adj1 = torch.from_numpy(adj1).float()\n",
    "        adj2 = torch.from_numpy(adj2).float()\n",
    "        adj1_o = torch.from_numpy(adj1_o).float()\n",
    "        adj2_o = torch.from_numpy(adj2_o).float()\n",
    "\n",
    "        return {'image': img,\n",
    "                'anim_obj': anim_obj,\n",
    "                'inanim_obj': inanim_obj,\n",
    "                'anim': anim,\n",
    "                'inanim': inanim,\n",
    "                'adj1':adj1,\n",
    "                'adj2':adj2,\n",
    "                'adj1_o':adj1_o,\n",
    "                'adj2_o':adj2_o}\n",
    "\n",
    "\n",
    "class RandomHorizontalFlip(object):\n",
    "    def __call__(self, sample):\n",
    "        img = sample['image']\n",
    "        anim_obj = sample['anim_obj']\n",
    "        inanim_obj = sample['inanim_obj']\n",
    "        anim = sample['anim']\n",
    "        inanim = sample['inanim']\n",
    "        adj1 = sample['adj1']\n",
    "        adj2 = sample['adj2']\n",
    "        adj1_o = sample['adj1_o']\n",
    "        adj2_o = sample['adj2_o']\n",
    "\n",
    "        if random.random() < 0.5:\n",
    "            img = img.transpose(Image.FLIP_LEFT_RIGHT)\n",
    "            anim_obj = anim_obj.transpose(Image.FLIP_LEFT_RIGHT)\n",
    "            inanim_obj = inanim_obj.transpose(Image.FLIP_LEFT_RIGHT)\n",
    "            anim = anim.transpose(Image.FLIP_LEFT_RIGHT)\n",
    "            inanim = inanim.transpose(Image.FLIP_LEFT_RIGHT)\n",
    "            adj2 = adj2.transpose(Image.FLIP_LEFT_RIGHT)\n",
    "            adj2_o = adj2_o.transpose(Image.FLIP_LEFT_RIGHT)\n",
    "\n",
    "            adj1 = adj1.transpose(Image.FLIP_LEFT_RIGHT)\n",
    "            adj1 = np.array(adj1).astype(np.float32)\n",
    "            adj1_flip = np.copy(adj1)\n",
    "            adj1_flip = adj1_flip + ((adj1 == 1) * 1) # 1 => 2\n",
    "            adj1_flip = adj1_flip - ((adj1 == 2) * 1) # 2 => 1\n",
    "            adj1 = Image.fromarray(adj1_flip)\n",
    "\n",
    "            adj1_o = adj1_o.transpose(Image.FLIP_LEFT_RIGHT)\n",
    "            adj1_o = np.array(adj1_o).astype(np.float32)\n",
    "            adj1_o_flip = np.copy(adj1_o)\n",
    "            adj1_o_flip = adj1_o_flip + ((adj1_o == 1) * 1) # 1 => 2\n",
    "            adj1_o_flip = adj1_o_flip - ((adj1_o == 2) * 1) # 2 => 1\n",
    "            adj1_o = Image.fromarray(adj1_o_flip)\n",
    "\n",
    "        return {'image': img,\n",
    "                'anim_obj': anim_obj,\n",
    "                'inanim_obj': inanim_obj,\n",
    "                'anim': anim,\n",
    "                'inanim': inanim,\n",
    "                'adj1':adj1,\n",
    "                'adj2':adj2,\n",
    "                'adj1_o':adj1_o,\n",
    "                'adj2_o':adj2_o}\n",
    "\n",
    "\n",
    "class RandomRotate(object):\n",
    "    def __init__(self, degree):\n",
    "        self.degree = degree\n",
    "\n",
    "    def __call__(self, sample):\n",
    "        img = sample['image']\n",
    "        anim_obj = sample['anim_obj']\n",
    "        inanim_obj = sample['inanim_obj']\n",
    "        anim = sample['anim']\n",
    "        inanim = sample['inanim']\n",
    "        adj1 = sample['adj1']\n",
    "        adj2 = sample['adj2']\n",
    "        adj1_o = sample['adj1_o']\n",
    "        adj2_o = sample['adj2_o']\n",
    "\n",
    "        rotate_degree = random.uniform(-1*self.degree, self.degree)\n",
    "        img = img.rotate(rotate_degree, Image.BILINEAR)\n",
    "        anim_obj = anim_obj.rotate(rotate_degree, Image.NEAREST)\n",
    "        inanim_obj = inanim_obj.rotate(rotate_degree, Image.NEAREST)\n",
    "        anim = anim.rotate(rotate_degree, Image.NEAREST)\n",
    "        inanim = inanim.rotate(rotate_degree, Image.NEAREST)\n",
    "        adj1 = adj1.rotate(rotate_degree, Image.NEAREST)\n",
    "        adj2 = adj2.rotate(rotate_degree, Image.NEAREST)\n",
    "        adj1_o = adj1_o.rotate(rotate_degree, Image.NEAREST)\n",
    "        adj2_o = adj2_o.rotate(rotate_degree, Image.NEAREST)\n",
    "\n",
    "        return {'image': img,\n",
    "                'anim_obj': anim_obj,\n",
    "                'inanim_obj': inanim_obj,\n",
    "                'anim': anim,\n",
    "                'inanim': inanim,\n",
    "                'adj1':adj1,\n",
    "                'adj2':adj2,\n",
    "                'adj1_o':adj1_o,\n",
    "                'adj2_o':adj2_o}\n",
    "\n",
    "\n",
    "class RandomGaussianBlur(object):\n",
    "    def __call__(self, sample):\n",
    "        img = sample['image']\n",
    "        anim_obj = sample['anim_obj']\n",
    "        inanim_obj = sample['inanim_obj']\n",
    "        anim = sample['anim']\n",
    "        inanim = sample['inanim']\n",
    "        adj1 = sample['adj1']\n",
    "        adj2 = sample['adj2']\n",
    "        adj1_o = sample['adj1_o']\n",
    "        adj2_o = sample['adj2_o']\n",
    "\n",
    "        if random.random() < 0.5:\n",
    "            img = img.filter(ImageFilter.GaussianBlur(\n",
    "                radius=random.random()))\n",
    "\n",
    "        return {'image': img,\n",
    "                'anim_obj': anim_obj,\n",
    "                'inanim_obj': inanim_obj,\n",
    "                'anim': anim,\n",
    "                'inanim': inanim,\n",
    "                'adj1':adj1,\n",
    "                'adj2':adj2,\n",
    "                'adj1_o':adj1_o,\n",
    "                'adj2_o':adj2_o}\n",
    "\n",
    "\n",
    "class RandomScaleCrop(object):\n",
    "    def __init__(self, base_size, crop_size, fill=0):\n",
    "        self.base_size = base_size\n",
    "        self.crop_size = crop_size\n",
    "        self.fill = fill\n",
    "\n",
    "    def __call__(self, sample):\n",
    "        img = sample['image']\n",
    "        anim_obj = sample['anim_obj']\n",
    "        inanim_obj = sample['inanim_obj']\n",
    "        anim = sample['anim']\n",
    "        inanim = sample['inanim']\n",
    "        adj1 = sample['adj1']\n",
    "        adj2 = sample['adj2']\n",
    "        adj1_o = sample['adj1_o']\n",
    "        adj2_o = sample['adj2_o']\n",
    "\n",
    "        # random scale (short edge)\n",
    "        short_size = random.randint(int(self.base_size * 0.5), int(self.base_size * 2.0))\n",
    "        w, h = img.size\n",
    "        if h > w:\n",
    "            ow = short_size\n",
    "            oh = int(1.0 * h * ow / w)\n",
    "        else:\n",
    "            oh = short_size\n",
    "            ow = int(1.0 * w * oh / h)\n",
    "        img = img.resize((ow, oh), Image.BILINEAR)\n",
    "        anim_obj = anim_obj.resize((ow, oh), Image.NEAREST)\n",
    "        inanim_obj = inanim_obj.resize((ow, oh), Image.NEAREST)\n",
    "        anim = anim.resize((ow, oh), Image.NEAREST)\n",
    "        inanim = inanim.resize((ow, oh), Image.NEAREST)\n",
    "        adj1 = adj1.resize((ow, oh), Image.NEAREST)\n",
    "        adj2 = adj2.resize((ow, oh), Image.NEAREST)\n",
    "        adj1_o = adj1_o.resize((ow, oh), Image.NEAREST)\n",
    "        adj2_o = adj2_o.resize((ow, oh), Image.NEAREST)\n",
    "\n",
    "        # pad crop\n",
    "        if short_size < self.crop_size:\n",
    "            padh = self.crop_size - oh if oh < self.crop_size else 0\n",
    "            padw = self.crop_size - ow if ow < self.crop_size else 0\n",
    "            img = ImageOps.expand(img, border=(0, 0, padw, padh), fill=0)\n",
    "            anim_obj = ImageOps.expand(anim_obj, border=(0, 0, padw, padh), fill=self.fill)\n",
    "            inanim_obj = ImageOps.expand(inanim_obj, border=(0, 0, padw, padh), fill=self.fill)\n",
    "            anim = ImageOps.expand(anim, border=(0, 0, padw, padh), fill=self.fill)\n",
    "            inanim = ImageOps.expand(inanim, border=(0, 0, padw, padh), fill=self.fill)\n",
    "            adj1 = ImageOps.expand(adj1, border=(0, 0, padw, padh), fill=self.fill)\n",
    "            adj2 = ImageOps.expand(adj2, border=(0, 0, padw, padh), fill=self.fill)\n",
    "            adj1_o = ImageOps.expand(adj1_o, border=(0, 0, padw, padh), fill=self.fill)\n",
    "            adj2_o = ImageOps.expand(adj2_o, border=(0, 0, padw, padh), fill=self.fill)\n",
    "\n",
    "        # random crop crop_size\n",
    "        w, h = img.size\n",
    "        x1 = random.randint(0, w - self.crop_size)\n",
    "        y1 = random.randint(0, h - self.crop_size)\n",
    "        img = img.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        anim_obj = anim_obj.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        inanim_obj = inanim_obj.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        anim = anim.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        inanim = inanim.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        adj1 = adj1.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        adj2 = adj2.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        adj1_o = adj1_o.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        adj2_o = adj2_o.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "\n",
    "        return {'image': img,\n",
    "                'anim_obj': anim_obj,\n",
    "                'inanim_obj': inanim_obj,\n",
    "                'anim': anim,\n",
    "                'inanim': inanim,\n",
    "                'adj1':adj1,\n",
    "                'adj2':adj2,\n",
    "                'adj1_o':adj1_o,\n",
    "                'adj2_o':adj2_o}\n",
    "\n",
    "\n",
    "class FixScaleCrop(object):\n",
    "    def __init__(self, crop_size):\n",
    "        self.crop_size = crop_size\n",
    "\n",
    "    def __call__(self, sample):\n",
    "        img = sample['image']\n",
    "        anim_obj = sample['anim_obj']\n",
    "        inanim_obj = sample['inanim_obj']\n",
    "        anim = sample['anim']\n",
    "        inanim = sample['inanim']\n",
    "        adj1 = sample['adj1']\n",
    "        adj2 = sample['adj2']\n",
    "        adj1_o = sample['adj1_o']\n",
    "        adj2_o = sample['adj2_o']\n",
    "\n",
    "        w, h = img.size\n",
    "        if w > h:\n",
    "            oh = self.crop_size\n",
    "            ow = int(1.0 * w * oh / h)\n",
    "        else:\n",
    "            ow = self.crop_size\n",
    "            oh = int(1.0 * h * ow / w)\n",
    "        img = img.resize((ow, oh), Image.BILINEAR)\n",
    "        anim_obj = anim_obj.resize((ow, oh), Image.NEAREST)\n",
    "        inanim_obj = inanim_obj.resize((ow, oh), Image.NEAREST)\n",
    "        anim = anim.resize((ow, oh), Image.NEAREST)\n",
    "        inanim = inanim.resize((ow, oh), Image.NEAREST)\n",
    "        adj1 = adj1.resize((ow, oh), Image.NEAREST)\n",
    "        adj2 = adj2.resize((ow, oh), Image.NEAREST)\n",
    "        adj1_o = adj1_o.resize((ow, oh), Image.NEAREST)\n",
    "        adj2_o = adj2_o.resize((ow, oh), Image.NEAREST)\n",
    "\n",
    "        # center crop\n",
    "        w, h = img.size\n",
    "        x1 = int(round((w - self.crop_size) / 2.))\n",
    "        y1 = int(round((h - self.crop_size) / 2.))\n",
    "        img = img.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        anim_obj = anim_obj.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        inanim_obj = inanim_obj.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        anim = anim.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        inanim = inanim.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        adj1 = adj1.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        adj2 = adj2.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        adj1_o = adj1_o.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "        adj2_o = adj2_o.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))\n",
    "\n",
    "        return {'image': img,\n",
    "                'anim_obj': anim_obj,\n",
    "                'inanim_obj': inanim_obj,\n",
    "                'anim': anim,\n",
    "                'inanim': inanim,\n",
    "                'adj1':adj1,\n",
    "                'adj2':adj2,\n",
    "                'adj1_o':adj1_o,\n",
    "                'adj2_o':adj2_o}\n",
    "\n",
    "class FixedResize(object):\n",
    "    def __init__(self, size):\n",
    "        self.size = (size, size)  # size: (h, w)\n",
    "\n",
    "    def __call__(self, sample):\n",
    "        img = sample['image']\n",
    "        anim_obj = sample['anim_obj']\n",
    "        inanim_obj = sample['inanim_obj']\n",
    "        anim = sample['anim']\n",
    "        inanim = sample['inanim']\n",
    "        adj1 = sample['adj1']\n",
    "        adj2 = sample['adj2']\n",
    "        adj1_o = sample['adj1_o']\n",
    "        adj2_o = sample['adj2_o']\n",
    "\n",
    "        # assert img.size == mask.size\n",
    "\n",
    "        img = img.resize(self.size, Image.BILINEAR)\n",
    "        anim_obj = anim_obj.resize(self.size, Image.NEAREST)\n",
    "        inanim_obj = inanim_obj.resize(self.size, Image.NEAREST)\n",
    "        anim = anim.resize(self.size, Image.NEAREST)\n",
    "        inanim = inanim.resize(self.size, Image.NEAREST)\n",
    "        adj1 = adj1.resize(self.size, Image.NEAREST)\n",
    "        adj2 = adj2.resize(self.size, Image.NEAREST)\n",
    "        adj1_o = adj1_o.resize(self.size, Image.NEAREST)\n",
    "        adj2_o = adj2_o.resize(self.size, Image.NEAREST)\n",
    "\n",
    "        return {'image': img,\n",
    "                'anim_obj': anim_obj,\n",
    "                'inanim_obj': inanim_obj,\n",
    "                'anim': anim,\n",
    "                'inanim': inanim,\n",
    "                'adj1':adj1,\n",
    "                'adj2':adj2,\n",
    "                'adj1_o':adj1_o,\n",
    "                'adj2_o':adj2_o}\n",
    "    \n",
    "class ResizeMasks(object):\n",
    "    def __init__(self, crop_size):\n",
    "        self.crop_size = crop_size\n",
    "\n",
    "    def __call__(self, sample):\n",
    "        img = sample['image']\n",
    "        anim_obj = sample['anim_obj']\n",
    "        inanim_obj = sample['inanim_obj']\n",
    "        anim = sample['anim']\n",
    "        inanim = sample['inanim']\n",
    "        adj1 = sample['adj1']\n",
    "        adj2 = sample['adj2']\n",
    "        adj1_o = sample['adj1_o']\n",
    "        adj2_o = sample['adj2_o']\n",
    "\n",
    "        w, h = img.size\n",
    "        short_size = 0\n",
    "        if w > h:\n",
    "            ow = self.crop_size\n",
    "            oh = int(1.0 * h * ow / w)\n",
    "            short_size = oh\n",
    "        else:\n",
    "            oh = self.crop_size\n",
    "            ow = int(1.0 * w * oh / h)\n",
    "            short_size = ow\n",
    "\n",
    "        img = img.resize((ow, oh), Image.BILINEAR)\n",
    "        anim_obj = anim_obj.resize((ow, oh), Image.NEAREST)\n",
    "        inanim_obj = inanim_obj.resize((ow, oh), Image.NEAREST)\n",
    "        anim = anim.resize((ow, oh), Image.NEAREST)\n",
    "        inanim = inanim.resize((ow, oh), Image.NEAREST)\n",
    "        adj1 = adj1.resize((ow, oh), Image.NEAREST)\n",
    "        adj2 = adj2.resize((ow, oh), Image.NEAREST)\n",
    "        adj1_o = adj1_o.resize((ow, oh), Image.NEAREST)\n",
    "        adj2_o = adj2_o.resize((ow, oh), Image.NEAREST)\n",
    "\n",
    "        if short_size < self.crop_size:\n",
    "            padh = self.crop_size - oh if oh < self.crop_size else 0\n",
    "            padw = self.crop_size - ow if ow < self.crop_size else 0\n",
    "            img = ImageOps.expand(img, border=(0, 0, padw, padh), fill=0)\n",
    "            anim_obj = ImageOps.expand(anim_obj, border=(0, 0, padw, padh), fill=0)\n",
    "            inanim_obj = ImageOps.expand(inanim_obj, border=(0, 0, padw, padh), fill=0)\n",
    "            anim = ImageOps.expand(anim, border=(0, 0, padw, padh), fill=0)\n",
    "            inanim = ImageOps.expand(inanim, border=(0, 0, padw, padh), fill=0)\n",
    "            adj1 = ImageOps.expand(adj1, border=(0, 0, padw, padh), fill=0)\n",
    "            adj2 = ImageOps.expand(adj2, border=(0, 0, padw, padh), fill=0)\n",
    "            adj1_o = ImageOps.expand(adj1_o, border=(0, 0, padw, padh), fill=0)\n",
    "            adj2_o = ImageOps.expand(adj2_o, border=(0, 0, padw, padh), fill=0)\n",
    "\n",
    "        return {'image': img,\n",
    "                'anim_obj': anim_obj,\n",
    "                'inanim_obj': inanim_obj,\n",
    "                'anim': anim,\n",
    "                'inanim': inanim,\n",
    "                'adj1':adj1,\n",
    "                'adj2':adj2,\n",
    "                'adj1_o':adj1_o,\n",
    "                'adj2_o':adj2_o}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Dataset class : manages animate/inanimate separation for images and labels.\n",
    "\"\"\"\n",
    "class SegmentationDataset(Dataset):\n",
    "    def __init__(self, folder, mode='train',\n",
    "                 input_shape=(513, 513), num_classes=201):\n",
    "\n",
    "        with open(folder + mode + '.txt') as f:\n",
    "            self.image_path_list = f.read().splitlines()\n",
    "\n",
    "        self.input_shape = input_shape\n",
    "        self.mode = mode\n",
    "        self.folder = folder\n",
    "        self.num_classes = num_classes\n",
    "        self.anim_aggregation_map = aggregate_parts_to_classes(num_classes, animate=True)\n",
    "        self.inanim_aggregation_map = aggregate_parts_to_classes(num_classes, animate=False)\n",
    "        self.anim_classes = [3, 8, 10, 12, 13, 15, 17]\n",
    "        self.inanim_classes = [1, 2, 4, 5, 6, 7, 9, 11, 14, 16, 18, 19, 20]\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.image_path_list)\n",
    "\n",
    "    def __getitem__(self, i):\n",
    "        \n",
    "        image_path = self.folder + 'images/' + self.image_path_list[i] + '.png'\n",
    "        part_label_path = self.folder + 'parts201/' + self.image_path_list[i] + '.png'\n",
    "        obj_label_path = self.folder + 'objs21/' + self.image_path_list[i] + '.png'\n",
    "\n",
    "        sample = {}\n",
    "        sample['image'] = Image.open(image_path)\n",
    "        org_size = sample['image'].size\n",
    "\n",
    "        part_label = np.array(Image.open(part_label_path))\n",
    "        anim_label = self.aggregate_anim_labels(part_label)\n",
    "        sample['anim'] = Image.fromarray(anim_label)\n",
    "        inanim_label = self.aggregate_inanim_labels(part_label)\n",
    "        sample['inanim'] = Image.fromarray(inanim_label)\n",
    "\n",
    "        obj_label = np.array(Image.open(obj_label_path))\n",
    "        anim_obj_label = self.anim_remove_objs(obj_label)\n",
    "        sample['anim_obj'] = Image.fromarray(anim_obj_label)\n",
    "        inanim_obj_label = self.inanim_remove_objs(obj_label)\n",
    "        sample['inanim_obj'] = Image.fromarray(inanim_obj_label)\n",
    "        \n",
    "        # Full adj\n",
    "        anim_lr_path = self.folder + 'full_adj201/animate/left_right/' + self.image_path_list[i] + '.png'\n",
    "        inanim_lr_path = self.folder + 'full_adj201/inanimate/left_right/' + self.image_path_list[i] + '.png'\n",
    "        anim_lr = np.array(Image.open(anim_lr_path))\n",
    "        inanim_lr = np.array(Image.open(inanim_lr_path))\n",
    "        overlap = (anim_lr > 0) * (inanim_lr > 0)\n",
    "        anim_lr -= anim_lr * overlap\n",
    "        sample['adj1'] = Image.fromarray(anim_lr + inanim_lr)\n",
    "        \n",
    "        anim_fb_path = self.folder + 'full_adj201/animate/front_back/' + self.image_path_list[i] + '.png'\n",
    "        inanim_fb_path = self.folder + 'full_adj201/inanimate/front_back/' + self.image_path_list[i] + '.png'\n",
    "        anim_fb = np.array(Image.open(anim_fb_path))\n",
    "        inanim_fb = np.array(Image.open(inanim_fb_path))\n",
    "        overlap = (anim_fb > 0) * (inanim_fb > 0)\n",
    "        anim_fb -= anim_fb * overlap\n",
    "        sample['adj2'] = Image.fromarray(anim_fb + inanim_fb)\n",
    "\n",
    "        # Adj\n",
    "        anim_lr_path = self.folder + 'adj201/animate/left_right/' + self.image_path_list[i] + '.png'\n",
    "        inanim_lr_path = self.folder + 'adj201/inanimate/left_right/' + self.image_path_list[i] + '.png'\n",
    "        anim_lr = np.array(Image.open(anim_lr_path))\n",
    "        inanim_lr = np.array(Image.open(inanim_lr_path))\n",
    "        overlap = (anim_lr > 0) * (inanim_lr > 0)\n",
    "        anim_lr -= anim_lr * overlap\n",
    "        sample['adj1_o'] = Image.fromarray(anim_lr + inanim_lr)\n",
    "\n",
    "        anim_fb_path = self.folder + 'adj201/animate/front_back/' + self.image_path_list[i] + '.png'\n",
    "        inanim_fb_path = self.folder + 'adj201/inanimate/front_back/' + self.image_path_list[i] + '.png'\n",
    "        anim_fb = np.array(Image.open(anim_fb_path))\n",
    "        inanim_fb = np.array(Image.open(inanim_fb_path))\n",
    "        overlap = (anim_fb > 0) * (inanim_fb > 0)\n",
    "        anim_fb -= anim_fb * overlap\n",
    "        sample['adj2_o'] = Image.fromarray(anim_fb + inanim_fb)\n",
    "\n",
    "        sample = self.transform_tr(sample)\n",
    "            \n",
    "        sample['path'] = self.image_path_list[i]\n",
    "        sample['orgsize'] = org_size\n",
    "\n",
    "        return sample\n",
    "\n",
    "    def anim_remove_objs(self, obj_label):\n",
    "        final_label = np.zeros(obj_label.shape)\n",
    "        for i in self.anim_classes:\n",
    "            obj = (obj_label == i)\n",
    "            obj = obj.astype(float)\n",
    "            final_label += (obj * i)\n",
    "\n",
    "        return final_label\n",
    "    \n",
    "    def inanim_remove_objs(self, obj_label):\n",
    "        final_label = np.zeros(obj_label.shape)\n",
    "        for i in self.inanim_classes:\n",
    "            obj = (obj_label == i)\n",
    "            obj = obj.astype(float)\n",
    "            final_label += (obj * i)\n",
    "\n",
    "        return final_label\n",
    "\n",
    "    def aggregate_anim_labels(self, part_label):\n",
    "        final_label = np.zeros(part_label.shape)\n",
    "        for i in range(self.num_classes):\n",
    "            part = (part_label == i)\n",
    "            part = part.astype(float)\n",
    "            final_label += self.anim_aggregation_map[i] * part\n",
    "\n",
    "        return final_label\n",
    "    \n",
    "    def aggregate_inanim_labels(self, part_label):\n",
    "        final_label = np.zeros(part_label.shape)\n",
    "        for i in range(self.num_classes):\n",
    "            part = (part_label == i)\n",
    "            part = part.astype(float)\n",
    "            final_label += self.inanim_aggregation_map[i] * part\n",
    "\n",
    "        return final_label\n",
    "\n",
    "    def transform_tr(self, sample):\n",
    "        composed_transforms = transforms.Compose([\n",
    "            RandomHorizontalFlip(),\n",
    "            RandomScaleCrop(base_size=513, crop_size=513),\n",
    "            RandomGaussianBlur(),\n",
    "            Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n",
    "            ToTensor()])\n",
    "\n",
    "        return composed_transforms(sample)\n",
    "\n",
    "    def transform_val(self, sample):\n",
    "        composed_transforms = transforms.Compose([\n",
    "            ResizeMasks(crop_size=770),\n",
    "            Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n",
    "            ToTensor()])\n",
    "\n",
    "        return composed_transforms(sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class LR_Scheduler(object):\n",
    "    \"\"\"Learning Rate Scheduler\n",
    "    Step mode: ``lr = baselr * 0.1 ^ {floor(epoch-1 / lr_step)}``\n",
    "    Cosine mode: ``lr = baselr * 0.5 * (1 + cos(iter/maxiter))``\n",
    "    Poly mode: ``lr = baselr * (1 - iter/maxiter) ^ 0.9``\n",
    "    Args:\n",
    "        args:\n",
    "          :attr:`args.lr_scheduler` lr scheduler mode (`cos`, `poly`),\n",
    "          :attr:`args.lr` base learning rate, :attr:`args.epochs` number of epochs,\n",
    "          :attr:`args.lr_step`\n",
    "        iters_per_epoch: number of iterations per epoch\n",
    "    \"\"\"\n",
    "    def __init__(self, mode, base_lr, num_epochs, iters_per_epoch=0,\n",
    "                 lr_step=0, warmup_epochs=0):\n",
    "        self.mode = mode\n",
    "        print('Using {} LR Scheduler!'.format(self.mode))\n",
    "        self.lr = base_lr\n",
    "        if mode == 'step':\n",
    "            assert lr_step\n",
    "        self.lr_step = lr_step\n",
    "        self.iters_per_epoch = iters_per_epoch\n",
    "        self.N = num_epochs * iters_per_epoch\n",
    "        self.epoch = -1\n",
    "        self.warmup_iters = warmup_epochs * iters_per_epoch\n",
    "\n",
    "    def __call__(self, optimizer, i, epoch):\n",
    "        T = epoch * self.iters_per_epoch + i\n",
    "        if self.mode == 'cos':\n",
    "            lr = 0.5 * self.lr * (1 + math.cos(1.0 * T / self.N * math.pi))\n",
    "        elif self.mode == 'poly':\n",
    "            lr = self.lr * pow((1 - 1.0 * T / self.N), 0.9)\n",
    "        elif self.mode == 'step':\n",
    "            lr = self.lr * (0.1 ** (epoch // self.lr_step))\n",
    "        else:\n",
    "            raise NotImplemented\n",
    "        # warm up lr schedule\n",
    "        if self.warmup_iters > 0 and T < self.warmup_iters:\n",
    "            lr = lr * 1.0 * T / self.warmup_iters\n",
    "        if epoch > self.epoch:\n",
    "            print('\\n=>Epoches %i, learning rate = %.4f' % (epoch, lr))\n",
    "            self.epoch = epoch\n",
    "        assert lr >= 0\n",
    "        self._adjust_learning_rate(optimizer, lr)\n",
    "\n",
    "    def _adjust_learning_rate(self, optimizer, lr):\n",
    "        if len(optimizer.param_groups) == 1:\n",
    "            optimizer.param_groups[0]['lr'] = lr\n",
    "        else:\n",
    "            # enlarge the lr at the head\n",
    "            optimizer.param_groups[0]['lr'] = lr\n",
    "            for i in range(1, len(optimizer.param_groups)):\n",
    "                optimizer.param_groups[i]['lr'] = lr * 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Number of animate and inanimate decoder heads.\n",
    "\"\"\"\n",
    "num_anim_classes = 24\n",
    "num_inanim_classes = 29"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Setting up training parameters : data path, batch_size and the training and validation datasets.\n",
    "\"\"\"\n",
    "\n",
    "PATH = '/path/to/dataset/'\n",
    "batch_size = 16\n",
    "\n",
    "train_dataset = SegmentationDataset(PATH)\n",
    "train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, drop_last=True, num_workers=4)\n",
    "valid_dataset = SegmentationDataset(PATH, mode='val')\n",
    "valid_dataloader = DataLoader(valid_dataset, batch_size=batch_size, shuffle=False, drop_last=False, num_workers=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = Float(backbone='resnet101', num_anim_classes=num_anim_classes, num_inanim_classes=num_inanim_classes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gpu_ids = [0,1,2,3,4,5,6,7]\n",
    "lr = 0.007\n",
    "\n",
    "train_params = [{'params': model.get_1x_lr_params(), 'lr': lr},\n",
    "                {'params': model.get_10x_lr_params(), 'lr': lr * 10}]\n",
    "\n",
    "optimizer = optim.SGD(train_params, momentum=0.9, weight_decay=1e-4)\n",
    "lr_scheduler = LR_Scheduler('poly', lr, 60, len(train_dataloader))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Parallezing the model deploying simultaneous training on multiple GPUs.\n",
    "\"\"\"\n",
    "if torch.cuda.device_count() > 1:\n",
    "    model = torch.nn.DataParallel(model, device_ids=gpu_ids)\n",
    "    patch_replication_callback(model)\n",
    "    model.cuda()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Model training.\n",
    "\"\"\"\n",
    "\n",
    "model.train()\n",
    "label_weights = torch.Tensor([0.3, 1.0, 1.0]).cuda()\n",
    "\n",
    "for epoch in range(60):\n",
    "    epoch_start = time.time()\n",
    "    train_loss_avg = AverageMeter()\n",
    "    anim_sqiou_avg = sqIOUMeter(num_anim_classes)\n",
    "    anim_miou_avg = Evaluator(num_anim_classes)\n",
    "    inanim_sqiou_avg = sqIOUMeter(num_inanim_classes)\n",
    "    inanim_miou_avg = Evaluator(num_inanim_classes)\n",
    "    # sqiogt --> sq Intersection over Ground Truth (not penalizing predicting extra)\n",
    "    adj1_sqiogt_avg = sqIOUMeter(2)\n",
    "    adj2_sqiogt_avg = sqIOUMeter(2)\n",
    "\n",
    "    tbar = tqdm(train_dataloader)\n",
    "    for i, sample in enumerate(tbar):\n",
    "        images = sample['image'].float()\n",
    "\n",
    "        anim_objs = sample['anim_obj'].type(torch.LongTensor)\n",
    "        anim_objs = anim_objs > 0\n",
    "        anim_objs = anim_objs.type(torch.LongTensor)\n",
    "\n",
    "        inanim_objs = sample['inanim_obj'].type(torch.LongTensor)\n",
    "        inanim_objs = inanim_objs > 0\n",
    "        inanim_objs = inanim_objs.type(torch.LongTensor)\n",
    "\n",
    "        anims = sample['anim'].type(torch.LongTensor)\n",
    "        inanims = sample['inanim'].type(torch.LongTensor)\n",
    "\n",
    "        adj1 = sample['adj1'].type(torch.LongTensor)\n",
    "        adj2 = sample['adj2'].type(torch.LongTensor)\n",
    "        adj1_o = sample['adj1_o'].type(torch.LongTensor)\n",
    "        adj2_o = sample['adj2_o'].type(torch.LongTensor)\n",
    "        nb = images.shape[0]\n",
    "\n",
    "        images = images.cuda()\n",
    "        anim_objs = anim_objs.cuda()\n",
    "        inanim_objs = inanim_objs.cuda()\n",
    "        anims = anims.cuda()\n",
    "        inanims = inanims.cuda()\n",
    "        adj1 = adj1.cuda()\n",
    "        adj2 = adj2.cuda()\n",
    "        adj1_o = adj1_o.cuda()\n",
    "        adj2_o = adj2_o.cuda()\n",
    "\n",
    "        lr_scheduler(optimizer, i, epoch)\n",
    "        optimizer.zero_grad()\n",
    "        anim_pred, inanim_pred, pred_adj1, pred_adj2 = model(images)\n",
    "\n",
    "        anim_ce_loss = crossentropy_loss(anim_pred, anims)\n",
    "        anim_graph_loss = adjacent_graph_loss(anim_pred, anims, num_anim_classes)\n",
    "        anim_obj_loss = objmask_loss(anim_pred, anim_objs, num_anim_classes)\n",
    "        \n",
    "        inanim_ce_loss = crossentropy_loss(inanim_pred, inanims)\n",
    "        inanim_graph_loss = adjacent_graph_loss(inanim_pred, inanims, num_inanim_classes)\n",
    "        inanim_obj_loss = objmask_loss(inanim_pred, inanim_objs, num_inanim_classes)\n",
    "\n",
    "        adj1_loss = crossentropy_loss(pred_adj1, adj1, lambda_loss=0.5, label_weights=label_weights)\n",
    "        adj2_loss = crossentropy_loss(pred_adj2, adj2, lambda_loss=0.5, label_weights=label_weights)\n",
    "\n",
    "        anim_loss = anim_ce_loss + anim_graph_loss + anim_obj_loss\n",
    "        inanim_loss = inanim_ce_loss + inanim_graph_loss + inanim_obj_loss\n",
    "        loss = anim_loss + inanim_loss + adj1_loss + adj2_loss\n",
    "\n",
    "        ious, counts = jaccard_perpart(anim_pred, anims, num_anim_classes)\n",
    "        for cl in range(num_anim_classes):\n",
    "            ious[cl] = ious[cl].item()\n",
    "            counts[cl] = counts[cl].item()\n",
    "        anim_sqiou_avg.update(ious, counts)\n",
    "\n",
    "        ious, counts = jaccard_perpart(inanim_pred, inanims, num_inanim_classes)\n",
    "        for cl in range(num_inanim_classes):\n",
    "            ious[cl] = ious[cl].item()\n",
    "            counts[cl] = counts[cl].item()\n",
    "        inanim_sqiou_avg.update(ious, counts)\n",
    "\n",
    "        ious, counts = iogt_perpart(pred_adj1, adj1_o, 3)\n",
    "        for cl in range(2):\n",
    "            ious[cl] = ious[cl].item()\n",
    "            counts[cl] = counts[cl].item()\n",
    "        adj1_sqiogt_avg.update(ious, counts)\n",
    "\n",
    "        ious, counts = iogt_perpart(pred_adj2, adj2_o, 3)\n",
    "        for cl in range(2):\n",
    "            ious[cl] = ious[cl].item()\n",
    "            counts[cl] = counts[cl].item()\n",
    "        adj2_sqiogt_avg.update(ious, counts)\n",
    "\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "        train_loss = loss.item()\n",
    "        train_loss_avg.update(train_loss, nb)\n",
    "\n",
    "        anims_ = anims.cpu().detach().numpy()\n",
    "        anim_pred_ = anim_pred.cpu().detach().numpy()\n",
    "        anim_pred_ = np.argmax(anim_pred_, 1)\n",
    "        anim_miou_avg.add_batch(anims_, anim_pred_)\n",
    "\n",
    "        inanims_ = inanims.cpu().detach().numpy()\n",
    "        inanim_pred_ = inanim_pred.cpu().detach().numpy()\n",
    "        inanim_pred_ = np.argmax(inanim_pred_, 1)\n",
    "        inanim_miou_avg.add_batch(inanims_, inanim_pred_)\n",
    "\n",
    "        tbar.set_description('a:%.4f, i:%.4f, lr:%.3f, fb:%.3f' % (anim_sqiou_avg.Mean_Intersection_over_Union(),\n",
    "                                                                   inanim_sqiou_avg.Mean_Intersection_over_Union(),\n",
    "                                                                   adj1_sqiogt_avg.avg,\n",
    "                                                                   adj2_sqiogt_avg.avg))\n",
    "\n",
    "    epoch_end = time.time()\n",
    "\n",
    "    print('Epoch:', epoch)\n",
    "    print('Loss    : {:.5f}'.format(loss.item()))\n",
    "    print('Loss Avg: {:.5f}'.format(train_loss_avg.avg))\n",
    "\n",
    "    print('Anim pqIOU   : {:.5f}'.format(anim_sqiou_avg.avg))\n",
    "    print('Anim mIOU    : {:.5f}'.format(anim_miou_avg.Mean_Intersection_over_Union()))\n",
    "\n",
    "    print('Inanim pqIOU   : {:.5f}'.format(inanim_sqiou_avg.avg))\n",
    "    print('Inanim mIOU    : {:.5f}'.format(inanim_miou_avg.Mean_Intersection_over_Union()))\n",
    "\n",
    "    print('Left    : {:.5f}'.format(adj1_sqiogt_avg.vals[0]/adj1_sqiogt_avg.counts[0]))\n",
    "    print('Right   : {:.5f}'.format(adj1_sqiogt_avg.vals[1]/adj1_sqiogt_avg.counts[1]))\n",
    "    print('LR      : {:.5f}'.format(adj1_sqiogt_avg.avg))\n",
    "\n",
    "    print('Front   : {:.5f}'.format(adj2_sqiogt_avg.vals[0]/adj2_sqiogt_avg.counts[0]))\n",
    "    print('Back    : {:.5f}'.format(adj2_sqiogt_avg.vals[1]/adj2_sqiogt_avg.counts[1]))\n",
    "    print('FB      : {:.5f}'.format(adj2_sqiogt_avg.avg))\n",
    "    print(\"Epoch time taken:\", str(epoch_end-epoch_start))\n",
    "    print('----------------------------------------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save trained model.\n",
    "torch.save(model.module.state_dict(), '/path/to/saved/model/destination')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
